Пример #1
0
        /// <summary>
        /// Import Rotation List
        /// </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 maxBlockIndex = 0;

            if (dbContext.HetRentalRequestRotationList.Any())
            {
                maxBlockIndex = dbContext.HetRentalRequestRotationList.Max(x => x.RentalRequestRotationListId);
            }

            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.Block[]), new XmlRootAttribute(rootAttr));
                MemoryStream         memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                ImportModels.Block[] legacyItems  = (ImportModels.Block[])ser.Deserialize(memoryStream);

                int ii = startPoint;

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

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

                foreach (ImportModels.Block item in legacyItems.WithProgress(progress))
                {
                    string areaId          = item.Area_Id.ToString();
                    string equipmentTypeId = item.Equip_Type_Id.ToString();
                    string createdDate     = item.Created_Dt;
                    string oldUniqueId     = string.Format("{0}-{1}-{2}", areaId, equipmentTypeId, createdDate);

                    // see if we have this one already
                    HetImportMap importMap = dbContext.HetImportMap.AsNoTracking()
                                             .FirstOrDefault(x => x.OldTable == OldTable &&
                                                             x.OldKey == oldUniqueId);

                    // new entry
                    if (importMap == null && item.Area_Id > 0)
                    {
                        HetLocalAreaRotationList instance = null;
                        CopyToInstance(dbContext, item, ref instance, systemId, ref maxBlockIndex);

                        if (instance != null)
                        {
                            ImportUtility.AddImportMap(dbContext, OldTable, oldUniqueId, NewTable, instance.LocalAreaRotationListId);
                        }
                    }

                    // save change to database
                    if (++ii % 2000 == 0)
                    {
                        ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BcBidImport.SigId, NewTable);
                        dbContext.SaveChangesForImport();
                    }
                }

                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 (BlockIndex: {0}): {1}", maxBlockIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
Пример #2
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;
            }
        }
Пример #3
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);
        }
Пример #4
0
        /// <summary>
        /// Update the Local Area Rotation List
        /// </summary>
        /// <param name="request"></param>
        /// <param name="numberOfBlocks"></param>
        /// <param name="context"></param>
        public static void UpdateRotationList(HetRentalRequest request, int numberOfBlocks, DbAppContext context)
        {
            // first get the localAreaRotationList.askNextBlock"N" for the given local area
            bool exists = context.HetLocalAreaRotationList.Any(a => a.LocalArea.LocalAreaId == request.LocalArea.LocalAreaId);

            HetLocalAreaRotationList localAreaRotationList;

            if (exists)
            {
                localAreaRotationList = context.HetLocalAreaRotationList
                                        .Include(x => x.LocalArea)
                                        .Include(x => x.AskNextBlock1)
                                        .Include(x => x.AskNextBlock2)
                                        .Include(x => x.AskNextBlockOpen)
                                        .FirstOrDefault(x => x.LocalArea.LocalAreaId == request.LocalArea.LocalAreaId &&
                                                        x.DistrictEquipmentTypeId == request.DistrictEquipmentTypeId);
            }
            else
            {
                localAreaRotationList = new HetLocalAreaRotationList
                {
                    LocalAreaId             = request.LocalAreaId,
                    DistrictEquipmentTypeId = request.DistrictEquipmentTypeId
                };
            }

            // determine what the next id is
            int?nextId = null;

            if (localAreaRotationList != null && localAreaRotationList.LocalAreaRotationListId > 0)
            {
                if (localAreaRotationList.AskNextBlock1Id != null)
                {
                    nextId = localAreaRotationList.AskNextBlock1Id;
                }
                else if (localAreaRotationList.AskNextBlock2Id != null)
                {
                    nextId = localAreaRotationList.AskNextBlock2Id;
                }
                else
                {
                    nextId = localAreaRotationList.AskNextBlockOpenId;
                }
            }

            // populate:
            // 1. the "next on the list" table for the Local Area  (HET_LOCAL_AREA_ROTATION_LIST)
            // 2. the first on the list id for the Rental Request  (HET_RENTAL_REQUEST.FIRST_ON_ROTATION_LIST_ID)
            if (request.HetRentalRequestRotationList.Count > 0)
            {
                request.HetRentalRequestRotationList = request.HetRentalRequestRotationList
                                                       .OrderBy(x => x.RotationListSortOrder).ToList();

                request.FirstOnRotationListId = request.HetRentalRequestRotationList.ElementAt(0).Equipment.EquipmentId;

                // find our next record
                int  nextRecordToAskIndex = 0;
                bool foundCurrentRecord   = false;

                if (nextId != null)
                {
                    for (int i = 0; i < request.HetRentalRequestRotationList.Count; i++)
                    {
                        bool forcedHire;
                        bool asked;

                        if (foundCurrentRecord &&
                            request.HetRentalRequestRotationList.ElementAt(i).IsForceHire != null &&
                            request.HetRentalRequestRotationList.ElementAt(i).IsForceHire == false)
                        {
                            forcedHire = false;
                        }
                        else if (foundCurrentRecord && request.HetRentalRequestRotationList.ElementAt(i).IsForceHire == null)
                        {
                            forcedHire = false;
                        }
                        else
                        {
                            forcedHire = true;
                        }

                        if (foundCurrentRecord &&
                            request.HetRentalRequestRotationList.ElementAt(i).OfferResponse != null &&
                            !request.HetRentalRequestRotationList.ElementAt(i).OfferResponse.Equals("Yes", StringComparison.InvariantCultureIgnoreCase) &&
                            !request.HetRentalRequestRotationList.ElementAt(i).OfferResponse.Equals("No", StringComparison.InvariantCultureIgnoreCase))
                        {
                            asked = false;
                        }
                        else if (foundCurrentRecord && request.HetRentalRequestRotationList.ElementAt(i).OfferResponse == null)
                        {
                            asked = false;
                        }
                        else
                        {
                            asked = true;
                        }

                        if (foundCurrentRecord && !forcedHire && !asked)
                        {
                            // we've found our next record - exit and update the lists
                            nextRecordToAskIndex = i;
                            break;
                        }

                        if (!foundCurrentRecord &&
                            request.HetRentalRequestRotationList.ElementAt(i).EquipmentId == nextId)
                        {
                            foundCurrentRecord = true;
                        }
                    }
                }

                if (request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.BlockNumber == 1 &&
                    request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.BlockNumber <= numberOfBlocks &&
                    localAreaRotationList != null)
                {
                    localAreaRotationList.AskNextBlock1Id        = request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.EquipmentId;
                    localAreaRotationList.AskNextBlock1Seniority = request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.Seniority;
                    localAreaRotationList.AskNextBlock2Id        = null;
                    localAreaRotationList.AskNextBlock2Seniority = null;
                    localAreaRotationList.AskNextBlockOpen       = null;
                    localAreaRotationList.AskNextBlockOpenId     = null;
                }
                else if (request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.BlockNumber == 2 &&
                         request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.BlockNumber <= numberOfBlocks &&
                         localAreaRotationList != null)
                {
                    localAreaRotationList.AskNextBlock2Id        = request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.EquipmentId;
                    localAreaRotationList.AskNextBlock2Seniority = request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.Seniority;
                    localAreaRotationList.AskNextBlock1Id        = null;
                    localAreaRotationList.AskNextBlock1Seniority = null;
                    localAreaRotationList.AskNextBlockOpen       = null;
                    localAreaRotationList.AskNextBlockOpenId     = null;
                }
                else if (localAreaRotationList != null)
                {
                    localAreaRotationList.AskNextBlockOpenId     = request.HetRentalRequestRotationList.ElementAt(nextRecordToAskIndex).Equipment.EquipmentId;
                    localAreaRotationList.AskNextBlock1Id        = null;
                    localAreaRotationList.AskNextBlock1Seniority = null;
                    localAreaRotationList.AskNextBlock2Id        = null;
                    localAreaRotationList.AskNextBlock2Seniority = null;
                }

                // save the list - Done!
                if (!exists)
                {
                    context.HetLocalAreaRotationList.Add(localAreaRotationList);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// New Rotation List
        /// * Find Record Number 1
        /// * Then update the Local Area Rotation List
        ///
        /// Business rules
        /// * is this the first request of the new fiscal year -> Yes: start from #1
        /// * get the "next equipment to be asked" from "LOCAL_AREA_ROTATION_LIST"
        ///   -> if this is Block 1 -> temporarily becomes #1 on the list
        ///   -> if not block 1 -> #1 i block 1 temporarily becomes #1 on the list
        /// * check all records before temporary #1
        ///   -> if a record was Force Hired -> make them #1
        /// </summary>
        /// <param name="rentalRequest"></param>
        /// <param name="numberOfBlocks"></param>
        /// <param name="context"></param>
        public static HetRentalRequest SetupNewRotationList(HetRentalRequest rentalRequest, int numberOfBlocks, DbAppContext context)
        {
            // nothing to do!
            if (rentalRequest.HetRentalRequestRotationList.Count <= 0)
            {
                return(rentalRequest);
            }

            // sort our new rotation list
            rentalRequest.HetRentalRequestRotationList = rentalRequest.HetRentalRequestRotationList
                                                         .OrderBy(x => x.RotationListSortOrder)
                                                         .ToList();

            // check if we have a localAreaRotationList.askNextBlock"N" for the given local area
            bool localAreaRotationListExists = context.HetLocalAreaRotationList
                                               .Any(a => a.LocalArea.LocalAreaId == rentalRequest.LocalAreaId);

            HetLocalAreaRotationList newAreaRotationList;

            if (localAreaRotationListExists)
            {
                newAreaRotationList = context.HetLocalAreaRotationList
                                      .First(a => a.LocalArea.LocalAreaId == rentalRequest.LocalAreaId);
            }
            else
            {
                // setup our new "local area rotation list"
                newAreaRotationList = new HetLocalAreaRotationList
                {
                    LocalAreaId             = rentalRequest.LocalAreaId,
                    DistrictEquipmentTypeId = rentalRequest.DistrictEquipmentTypeId
                };
            }

            // determine current fiscal year - check for existing rotation lists this year
            DateTime fiscalStart;

            if (DateTime.UtcNow.Month == 1 || DateTime.UtcNow.Month == 2 || DateTime.UtcNow.Month == 3)
            {
                fiscalStart = new DateTime(DateTime.UtcNow.AddYears(-1).Year, 4, 1);
            }
            else
            {
                fiscalStart = new DateTime(DateTime.UtcNow.Year, 4, 1);
            }

            // get the last rotation list created this fiscal year
            bool previousRequestExists = context.HetRentalRequest
                                         .Any(x => x.DistrictEquipmentType.DistrictEquipmentTypeId == rentalRequest.DistrictEquipmentTypeId &&
                                              x.LocalArea.LocalAreaId == rentalRequest.LocalAreaId &&
                                              x.AppCreateTimestamp >= fiscalStart);

            // *****************************************************************
            // if we don't have a request
            // ** remove hired equipment
            // ** pick block 1 / record 1 & we're done
            // *****************************************************************
            if (!previousRequestExists)
            {
                // remove hired equipment from the list
                rentalRequest = DropHiredEquipment(rentalRequest, context);

                rentalRequest.FirstOnRotationListId = rentalRequest.HetRentalRequestRotationList.ElementAt(0).EquipmentId;

                int block = numberOfBlocks;

                if (rentalRequest.HetRentalRequestRotationList.ElementAt(0).BlockNumber != null)
                {
                    int?equipmentBlockNumber = rentalRequest.HetRentalRequestRotationList.ElementAt(0).BlockNumber;
                    if (equipmentBlockNumber != null)
                    {
                        block = (int)equipmentBlockNumber;
                    }
                }

                // update local area rotation list
                newAreaRotationList = UpdateNextRecordToAsk(block,
                                                            rentalRequest.HetRentalRequestRotationList.ElementAt(0).EquipmentId,
                                                            rentalRequest.HetRentalRequestRotationList.ElementAt(0).SeniorityFloat,
                                                            newAreaRotationList);

                // save rotation list
                if (localAreaRotationListExists)
                {
                    context.HetLocalAreaRotationList.Update(newAreaRotationList);
                }
                else
                {
                    context.HetLocalAreaRotationList.Add(newAreaRotationList);
                }

                return(rentalRequest); //done!
            }

            // *****************************************************************
            // use the previous rotation list to determine where we were
            // ** we pick the record after the last "asked" (Yes/No)
            // ** if all records in that block were "asked" - then we need to
            //    move on to the next block
            // ** also need to check if the equipment is currently hired
            // *****************************************************************
            int[]   nextRecordToAskIndex     = new int[numberOfBlocks];
            int[]   nextRecordToAskId        = new int[numberOfBlocks];
            int[]   nextRecordToAskBlock     = new int[numberOfBlocks];
            float[] nextRecordToAskSeniority = new float[numberOfBlocks];
            int     startBlock = -1;

            for (int b = 0; b < numberOfBlocks; b++)
            {
                nextRecordToAskIndex[b] = -1;
                nextRecordToAskId[b]    = -1;
                nextRecordToAskBlock[b] = -1;

                // get the last asked equipment id for this "block"
                HetEquipment lastEquipment = LastAskedByBlock(b, rentalRequest.DistrictEquipmentTypeId, rentalRequest.LocalAreaId,
                                                              fiscalStart, context);

                // nothing found for this block - start at 0
                if (lastEquipment == null && rentalRequest.HetRentalRequestRotationList.Count > 0)
                {
                    for (int j = 0; j < rentalRequest.HetRentalRequestRotationList.Count; j++)
                    {
                        if (rentalRequest.HetRentalRequestRotationList.ElementAt(j).BlockNumber != (b + 1))
                        {
                            continue;                                                                                 // move to next record
                        }
                        if (!IsEquipmentHired(rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId, context))
                        {
                            int temp = rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId ?? -1;

                            if (temp > -1)
                            {
                                nextRecordToAskId[b]    = temp;
                                nextRecordToAskBlock[b] = b;

                                break;
                            }
                        }
                    }
                }

                // find the next record - and ensure it's not currently hired
                bool foundLast = false;

                for (int j = 0; j < rentalRequest.HetRentalRequestRotationList.Count; j++)
                {
                    // make sure we're working in the right block
                    if (rentalRequest.HetRentalRequestRotationList.ElementAt(j).Equipment.BlockNumber != (b + 1))
                    {
                        continue;                                                                                           // move to next record
                    }
                    if (foundLast)
                    {
                        if (!IsEquipmentHired(rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId, context))
                        {
                            int temp = rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId ?? -1;

                            if (temp > -1)
                            {
                                nextRecordToAskId[b]    = temp;
                                nextRecordToAskBlock[b] = b;
                                break;
                            }
                        }
                    }

                    foundLast = rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId == lastEquipment?.EquipmentId;
                }
            }

            // *****************************************************************
            // 2. Remove all hired equipment from the new list
            // *****************************************************************
            rentalRequest = DropHiredEquipment(rentalRequest, context);

            // locate our "start" records in the updated list
            for (int b = 0; b < numberOfBlocks; b++)
            {
                if (nextRecordToAskId[b] > 0)
                {
                    for (int j = 0; j < rentalRequest.HetRentalRequestRotationList.Count; j++)
                    {
                        // make sure we're working in the right block
                        if (rentalRequest.HetRentalRequestRotationList.ElementAt(j).Equipment.BlockNumber != (b + 1))
                        {
                            continue;                                                                                           // move to next record
                        }
                        if (rentalRequest.HetRentalRequestRotationList.ElementAt(j).EquipmentId == nextRecordToAskId[b])
                        {
                            nextRecordToAskIndex[b] = j;
                            if (startBlock == -1)
                            {
                                startBlock = b;
                            }
                            break;
                        }
                    }
                }
            }

            // check we have equipment still after removing everything
            if (rentalRequest.HetRentalRequestRotationList.Count <= 0)
            {
                throw new ArgumentException("HETS-35"); // no more records available
            }

            // *****************************************************************
            // 3. Default the index to the first record if nothing is selected
            // *****************************************************************
            for (int b = 0; b < numberOfBlocks; b++)
            {
                if (nextRecordToAskIndex[b] < 0)
                {
                    if (rentalRequest.HetRentalRequestRotationList.ElementAt(0) != null)
                    {
                        nextRecordToAskIndex[b] = 0;
                        nextRecordToAskId[b]    = rentalRequest.HetRentalRequestRotationList.ElementAt(0).Equipment.EquipmentId;

                        if (rentalRequest.HetRentalRequestRotationList.ElementAt(0).Equipment.Seniority == null)
                        {
                            nextRecordToAskSeniority[b] = 0.0F;
                        }
                        else
                        {
                            float?equipmentSeniority = rentalRequest.HetRentalRequestRotationList.ElementAt(0).Equipment.Seniority;
                            if (equipmentSeniority != null)
                            {
                                nextRecordToAskSeniority[b] = (float)equipmentSeniority;
                            }
                        }

                        if (startBlock == -1)
                        {
                            startBlock = b;
                        }
                        break; // done
                    }
                }
            }

            // *****************************************************************
            // 4. Update the local area rotation list
            // *****************************************************************
            rentalRequest.FirstOnRotationListId = nextRecordToAskId[startBlock];

            // update local area rotation list
            newAreaRotationList = UpdateNextRecordToAsk(nextRecordToAskBlock[startBlock],
                                                        nextRecordToAskId[startBlock],
                                                        nextRecordToAskSeniority[startBlock],
                                                        newAreaRotationList);

            // *****************************************************************
            // 5. Reset the rotation list sort order
            //    ** starting @ nextRecordToAskIndex
            // *****************************************************************
            int masterSortOrder = 0;

            // process the start block first
            for (int i = nextRecordToAskIndex[startBlock]; i < rentalRequest.HetRentalRequestRotationList.Count; i++)
            {
                if (rentalRequest.HetRentalRequestRotationList.ElementAt(i).BlockNumber != startBlock)
                {
                    break; // done with the start block / start index to end of block
                }

                masterSortOrder++;
                rentalRequest.HetRentalRequestRotationList.ElementAt(i).RotationListSortOrder = masterSortOrder;
            }

            // finish the "first set" of records in the start block (before the index)
            for (int i = 0; i < nextRecordToAskIndex[startBlock]; i++)
            {
                if (rentalRequest.HetRentalRequestRotationList.ElementAt(i).BlockNumber != startBlock)
                {
                    continue; // move to the next record
                }

                masterSortOrder++;
                rentalRequest.HetRentalRequestRotationList.ElementAt(i).RotationListSortOrder = masterSortOrder;
            }

            // process other blocks
            for (int b = 0; b < numberOfBlocks; b++)
            {
                if (b + 1 == startBlock)
                {
                    continue;                      // already processed
                }
                for (int i = nextRecordToAskIndex[b]; i < rentalRequest.HetRentalRequestRotationList.Count; i++)
                {
                    if (i < 0 || rentalRequest.HetRentalRequestRotationList.ElementAt(i).BlockNumber != b + 1)
                    {
                        continue; // move to the next record
                    }

                    masterSortOrder++;
                    rentalRequest.HetRentalRequestRotationList.ElementAt(i).RotationListSortOrder = masterSortOrder;
                }

                // finish the "first set" of records in the block (before the index)
                for (int i = 0; i < nextRecordToAskIndex[b]; i++)
                {
                    if (rentalRequest.HetRentalRequestRotationList.ElementAt(i).BlockNumber != b + 1)
                    {
                        continue; // move to the next record
                    }

                    masterSortOrder++;
                    rentalRequest.HetRentalRequestRotationList.ElementAt(i).RotationListSortOrder = masterSortOrder;
                }
            }

            // add the new list
            if (!localAreaRotationListExists)
            {
                context.HetLocalAreaRotationList.Add(newAreaRotationList);
            }

            return(rentalRequest);
        }
Пример #6
0
        private static HetLocalAreaRotationList UpdateNextRecordToAsk(int block, int?equipmentId, float?seniority, HetLocalAreaRotationList rotationList)
        {
            if (block == 1)
            {
                rotationList.AskNextBlock1Id        = equipmentId;
                rotationList.AskNextBlock1Seniority = seniority;
                rotationList.AskNextBlock2Id        = null;
                rotationList.AskNextBlock2Seniority = null;
                rotationList.AskNextBlockOpenId     = null;
            }
            else if (block == 2)
            {
                rotationList.AskNextBlock1Id        = null;
                rotationList.AskNextBlock1Seniority = null;
                rotationList.AskNextBlock2Id        = equipmentId;
                rotationList.AskNextBlock2Seniority = seniority;
                rotationList.AskNextBlockOpenId     = null;
            }
            else
            {
                rotationList.AskNextBlock1Id        = null;
                rotationList.AskNextBlock1Seniority = null;
                rotationList.AskNextBlock2Id        = null;
                rotationList.AskNextBlock2Seniority = null;
                rotationList.AskNextBlockOpenId     = equipmentId;
            }

            return(rotationList);
        }
        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)));
        }