private static bool AddedToBlock(int currentBlock, int totalBlocks, int blockSize,
                                         List <int>[] blocks, HetEquipment equipment, DbAppContext context, bool saveChanges = true)
        {
            try
            {
                // check if this record's Owner is null
                if (equipment.Owner == null)
                {
                    return(false); // not adding this record to the block
                }

                if (blocks[currentBlock] == null)
                {
                    blocks[currentBlock] = new List <int>();
                }

                // check if the current block is full
                if (currentBlock < (totalBlocks - 1) && blocks[currentBlock].Count >= blockSize)
                {
                    return(false); // not adding this record to the block
                }

                // check if this record's Owner already exists in the block
                if (currentBlock < (totalBlocks - 1) && blocks[currentBlock].Contains(equipment.Owner.OwnerId))
                {
                    return(false); // not adding this record to the block
                }

                // (HETS-877) check if this is a maintenance contractor - can only be in the last block
                if (currentBlock < (totalBlocks - 1) &&
                    equipment.Owner.IsMaintenanceContractor != null &&
                    equipment.Owner.IsMaintenanceContractor == true)
                {
                    return(false); // not adding this record to the block
                }

                // add record to the block
                blocks[currentBlock].Add(equipment.Owner.OwnerId);

                // update the equipment record
                equipment.BlockNumber   = currentBlock + 1;
                equipment.NumberInBlock = blocks[currentBlock].Count;

                context.HetEquipment.Update(equipment);

                if (saveChanges)
                {
                    context.SaveChanges();
                }

                // record added to the block
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: AddedToBlock");
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Get rental agreement
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetRentalAgreementNumber(HetEquipment equipment, DbAppContext context)
        {
            string result = "";

            // validate item.
            if (equipment?.LocalArea != null)
            {
                DateTime currentTime = DateTime.UtcNow;

                int fiscalYear = currentTime.Year;

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

                int localAreaNumber = equipment.LocalArea.LocalAreaNumber;
                int localAreaId     = equipment.LocalArea.LocalAreaId;

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

                // count the number of rental agreements in the system
                int currentCount = context.HetRentalAgreement
                                   .Include(x => x.Equipment.LocalArea)
                                   .Count(x => x.Equipment.LocalArea.LocalAreaId == localAreaId && x.AppCreateTimestamp >= fiscalYearStart);

                currentCount++;

                // format of the Rental Agreement number is YYYY-#-####
                result = fiscalYear + "-" + localAreaNumber + "-" + currentCount.ToString("D4");
            }

            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// Get an Equipment record
        /// </summary>
        /// <param name="id"></param>
        /// <param name="context"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static HetEquipment GetRecord(int id, DbAppContext context, IConfiguration configuration)
        {
            // retrieve updated equipment record to return to ui
            HetEquipment equipment = context.HetEquipment.AsNoTracking()
                                     .Include(x => x.EquipmentStatusType)
                                     .Include(x => x.LocalArea)
                                     .ThenInclude(y => y.ServiceArea)
                                     .ThenInclude(z => z.District)
                                     .ThenInclude(a => a.Region)
                                     .Include(x => x.DistrictEquipmentType)
                                     .ThenInclude(d => d.EquipmentType)
                                     .Include(x => x.Owner)
                                     .ThenInclude(x => x.OwnerStatusType)
                                     .Include(x => x.HetEquipmentAttachment)
                                     .Include(x => x.HetNote)
                                     .Include(x => x.HetDigitalFile)
                                     .Include(x => x.HetHistory)
                                     .FirstOrDefault(a => a.EquipmentId == id);

            if (equipment != null)
            {
                equipment.IsHired        = IsHired(id, context);
                equipment.NumberOfBlocks = GetNumberOfBlocks(equipment, configuration);
                equipment.HoursYtd       = GetYtdServiceHours(id, context);
                equipment.Status         = equipment.EquipmentStatusType.EquipmentStatusTypeCode;

                if (equipment.Seniority != null && equipment.BlockNumber != null)
                {
                    equipment.SeniorityString = FormatSeniorityString((float)equipment.Seniority, (int)equipment.BlockNumber, equipment.NumberOfBlocks);
                }

                if (equipment.Owner != null)
                {
                    // populate the "Status" description
                    equipment.Owner.Status = equipment.Owner.OwnerStatusType.OwnerStatusTypeCode;
                }

                // set fiscal year headers
                if (equipment.LocalArea?.ServiceArea?.District != null)
                {
                    int districtId = equipment.LocalArea.ServiceArea.District.DistrictId;

                    HetDistrictStatus district = context.HetDistrictStatus.AsNoTracking()
                                                 .FirstOrDefault(x => x.DistrictId == districtId);

                    if (district?.NextFiscalYear != null)
                    {
                        int fiscalYear = (int)district.NextFiscalYear; // status table uses the start of the tear

                        equipment.YearMinus1 = string.Format("{0}/{1}", fiscalYear - 2, fiscalYear - 1);
                        equipment.YearMinus2 = string.Format("{0}/{1}", fiscalYear - 3, fiscalYear - 2);
                        equipment.YearMinus3 = string.Format("{0}/{1}", fiscalYear - 4, fiscalYear - 3);
                    }
                }
            }

            return(equipment);
        }
        /// <summary>
        /// Get rental agreement
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetRentalAgreementNumber(HetEquipment equipment, DbAppContext context)
        {
            string result = "";

            // validate item.
            if (equipment?.LocalArea != null)
            {
                int localAreaId = equipment.LocalArea.LocalAreaId;

                // get the district
                HetLocalArea localArea = context.HetLocalArea.AsNoTracking()
                                         .Include(x => x.ServiceArea)
                                         .ThenInclude(y => y.District)
                                         .First(x => x.LocalAreaId == localAreaId);

                int?districtId         = localArea.ServiceArea.DistrictId;
                int ministryDistrictId = localArea.ServiceArea.District.MinistryDistrictId;
                if (districtId == null)
                {
                    return(result);
                }

                // get fiscal year
                HetDistrictStatus status = context.HetDistrictStatus.AsNoTracking()
                                           .First(x => x.DistrictId == districtId);

                int?fiscalYear = status.CurrentFiscalYear;
                if (fiscalYear == null)
                {
                    return(result);
                }

                // fiscal year in the status table stores the "start" of the year
                DateTime fiscalYearStart = new DateTime((int)fiscalYear, 4, 1);
                fiscalYear = fiscalYear + 1;

                // count the number of rental agreements in the system in this district
                int currentCount = context.HetRentalAgreement
                                   .Count(x => x.DistrictId == districtId &&
                                          x.AppCreateTimestamp >= fiscalYearStart);

                currentCount++;

                // format of the Rental Agreement number is:
                // * FY-DD-####
                //   FY = last 2 digits of the year
                //   DD - District(2 digits - 1 to 11)
                result = fiscalYear.ToString().Substring(2, 2) + "-" +
                         ministryDistrictId + "-" +
                         currentCount.ToString("D4");
            }

            return(result);
        }
        public virtual IActionResult EquipmentIdAttachmentsPost([FromRoute] int id, [FromForm] IList <IFormFile> files)
        {
            // validate the id
            bool exists = _context.HetEquipment.Any(a => a.EquipmentId == id);

            if (!exists)
            {
                return(new StatusCodeResult(404));
            }

            HetEquipment equipment = _context.HetEquipment
                                     .Include(x => x.HetDigitalFile)
                                     .First(a => a.EquipmentId == id);

            foreach (IFormFile file in files)
            {
                if (file.Length > 0)
                {
                    HetDigitalFile attachment = new HetDigitalFile();

                    // strip out extra info in the file name
                    if (!string.IsNullOrEmpty(file.FileName))
                    {
                        attachment.FileName = Path.GetFileName(file.FileName);
                    }

                    // allocate storage for the file and create a memory stream
                    attachment.FileContents = new byte[file.Length];

                    using (MemoryStream fileStream = new MemoryStream(attachment.FileContents))
                    {
                        file.CopyTo(fileStream);
                    }

                    attachment.Type = GetType(attachment.FileName);

                    // set the mime type id
                    int?mimeTypeId = StatusHelper.GetMimeTypeId(attachment.Type, _context);
                    if (mimeTypeId == null)
                    {
                        throw new DataException("Mime Type Id cannot be null");
                    }

                    attachment.MimeTypeId = (int)mimeTypeId;

                    equipment.HetDigitalFile.Add(attachment);
                }
            }

            _context.SaveChanges();

            return(new ObjectResult(equipment.HetDigitalFile));
        }
Beispiel #6
0
        /// <summary>
        /// Set the Equipment fields for a new record for fields that are not provided by the front end
        /// </summary>
        /// <param name="item"></param>
        /// <param name="context"></param>
        public static HetEquipment SetNewRecordFields(HetEquipment item, DbAppContext context)
        {
            item.ReceivedDate     = DateTime.UtcNow;
            item.LastVerifiedDate = DateTime.UtcNow;

            // per JIRA HETS-536
            item.ApprovedDate = DateTime.UtcNow;

            item.Seniority                 = 0.0F;
            item.YearsOfService            = 0.0F;
            item.ServiceHoursLastYear      = 0.0F;
            item.ServiceHoursTwoYearsAgo   = 0.0F;
            item.ServiceHoursThreeYearsAgo = 0.0F;
            item.ArchiveCode               = "N";
            item.IsSeniorityOverridden     = false;

            int tmpAreaId = item.LocalArea.LocalAreaId;

            item.LocalAreaId = tmpAreaId;
            item.LocalArea   = null;

            int tmpEquipId = item.DistrictEquipmentType.DistrictEquipmentTypeId;

            item.DistrictEquipmentTypeId = tmpEquipId;
            item.DistrictEquipmentType   = null;

            // [Original: new equipment MUST always start as unapproved - it isn't assigned to any block yet]
            // HETS-834 - BVT - New Equipment Added default to APPROVED
            // * Set to Approved
            // * Update all equipment blocks, etc.
            int?statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", context);

            if (statusId == null)
            {
                throw new DataException("Status Id cannot be null");
            }

            item.EquipmentStatusTypeId = (int)statusId;

            // generate a new equipment code
            if (item.Owner != null)
            {
                // set the equipment code
                item.EquipmentCode = GetEquipmentCode(item.Owner.OwnerId, context);

                // cleanup owner reference
                int tmpOwnerId = item.Owner.OwnerId;
                item.OwnerId = tmpOwnerId;
                item.Owner   = null;
            }

            return(item);
        }
Beispiel #7
0
        /// <summary>
        /// Get the number of blocks for the equipment type
        /// </summary>
        /// <param name="item"></param>
        /// <param name="configuration"></param>
        public static int GetNumberOfBlocks(HetEquipment item, IConfiguration configuration)
        {
            int numberOfBlocks = -1;

            try
            {
                SeniorityScoringRules scoringRules = new SeniorityScoringRules(configuration);

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

            return(numberOfBlocks);
        }
Beispiel #8
0
        /// <summary>
        /// Get the YTD service hours for a piece of equipment
        /// </summary>
        /// <param name="id"></param>
        /// <param name="context"></param>
        /// <param name="rolloverDate"></param>
        public static float GetYtdServiceHours(int id, DbAppContext context, DateTime?rolloverDate = null)
        {
            float result = 0.0F;

            // *******************************************************************************
            // determine current fiscal year - check for existing rotation lists this year
            // * the rollover uses the dates from the status table (rolloverDate)
            // *******************************************************************************
            HetEquipment equipment = context.HetEquipment.AsNoTracking()
                                     .Include(x => x.LocalArea.ServiceArea.District)
                                     .First(x => x.EquipmentId == id);

            HetDistrictStatus district = context.HetDistrictStatus.AsNoTracking()
                                         .First(x => x.DistrictId == equipment.LocalArea.ServiceArea.DistrictId);

            if (district?.NextFiscalYear == null)
            {
                throw new ArgumentException("Error retrieving district status record");
            }

            int      fiscalYear  = (int)district.NextFiscalYear; // status table uses the start of the year
            DateTime fiscalEnd   = new DateTime(fiscalYear, 3, 31);
            DateTime fiscalStart = new DateTime(fiscalYear - 1, 4, 1);

            // *******************************************************************************
            // get all the time data for the current fiscal year
            // *******************************************************************************
            float?summation = context.HetTimeRecord.AsNoTracking()
                              .Include(x => x.RentalAgreement.Equipment)
                              .Where(x => x.RentalAgreement.EquipmentId == id &&
                                     x.WorkedDate >= fiscalStart &&
                                     x.WorkedDate <= fiscalEnd)
                              .Sum(x => x.Hours);

            if (summation != null)
            {
                result = (float)summation;
            }

            return(result);
        }
Beispiel #9
0
        public static List <History> GetHistoryRecords(int id, int?offset, int?limit, DbAppContext context)
        {
            HetEquipment equipment = context.HetEquipment.AsNoTracking()
                                     .Include(x => x.HetHistory)
                                     .First(a => a.EquipmentId == id);

            List <HetHistory> data = equipment.HetHistory
                                     .OrderByDescending(y => y.AppLastUpdateTimestamp)
                                     .ToList();

            if (offset == null)
            {
                offset = 0;
            }

            if (limit == null)
            {
                limit = data.Count - offset;
            }

            List <History> result = new List <History>();

            for (int i = (int)offset; i < data.Count && i < offset + limit; i++)
            {
                History temp = new History();

                if (data[i] != null)
                {
                    temp.HistoryText         = data[i].HistoryText;
                    temp.Id                  = data[i].HistoryId;
                    temp.LastUpdateTimestamp = data[i].AppLastUpdateTimestamp;
                    temp.LastUpdateUserid    = data[i].AppLastUpdateUserid;
                    temp.AffectedEntityId    = data[i].EquipmentId;
                }

                result.Add(temp);
            }

            return(result);
        }
Beispiel #10
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;
            }
        }
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipAttach"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipAttachIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.EquipAttach oldObject,
                                           ref HetEquipmentAttachment equipAttach, string systemId, ref int maxEquipAttachIndex)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                equipAttach = new HetEquipmentAttachment {
                    EquipmentAttachmentId = ++maxEquipAttachIndex
                };

                // ************************************************
                // get the imported equipment record map
                // ************************************************
                string tempId = oldObject.Equip_Id.ToString();

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

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

                // ************************************************
                // get the equipment record
                // ************************************************
                HetEquipment equipment = dbContext.HetEquipment.AsNoTracking()
                                         .FirstOrDefault(x => x.EquipmentId == map.NewKey);

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

                // ************************************************
                // set the equipment attachment attributes
                // ************************************************
                int tempEquipmentId = equipment.EquipmentId;
                equipAttach.EquipmentId = tempEquipmentId;

                string tempDescription = ImportUtility.CleanString(oldObject.Attach_Desc);

                if (string.IsNullOrEmpty(tempDescription))
                {
                    return;                                        // don't add blank attachments
                }
                tempDescription = ImportUtility.GetCapitalCase(tempDescription);

                // populate Name and Description with the same value
                equipAttach.Description = tempDescription;
                equipAttach.TypeName    = tempDescription;

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

                dbContext.HetEquipmentAttachment.Add(equipAttach);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Attachment: " + equipAttach.Description);
                Debug.WriteLine("***Error*** - Master Equipment Attachment Index: " + maxEquipAttachIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #12
0
        public static string GetEquipmentCode(int ownerId, DbAppContext context)
        {
            // get equipment owner
            HetOwner owner = context.HetOwner.AsNoTracking()
                             .FirstOrDefault(x => x.OwnerId == ownerId);

            if (owner != null)
            {
                string ownerCode       = owner.OwnerCode;
                int    equipmentNumber = 1;

                // get the last "added" equipment record
                // 1. convert code to numeric (extract the numeric portion)
                List <EquipmentCodeModel> equipmentList = (
                    from equip in context.HetEquipment
                    where equip.OwnerId == owner.OwnerId &&
                    equip.EquipmentCode.StartsWith(owner.OwnerCode)
                    select new EquipmentCodeModel
                {
                    EquipmentId = equip.EquipmentId,
                    EquipmentCode = equip.EquipmentCode
                })
                                                          .AsNoTracking()
                                                          .ToList();

                if (equipmentList.Any())
                {
                    foreach (EquipmentCodeModel equipment in equipmentList)
                    {
                        // TH-51215 Dupilicate Equipment IDs
                        // The previous code causes incorrect sorting when owner code containers numeric characters
                        string equipmentCode = equipment.EquipmentCode.Replace(ownerCode, "");

                        equipment.EquipmentNumber = int.Parse(Regex.Match(equipmentCode, @"\d+").Value);
                    }

                    // 2. sort by the numeric and get last equipment
                    equipmentList = equipmentList.OrderByDescending(x => x.EquipmentNumber).ToList();

                    // 3. get last equipment
                    HetEquipment lastEquipment = context.HetEquipment.AsNoTracking()
                                                 .FirstOrDefault(x => x.EquipmentId == equipmentList[0].EquipmentId);

                    if (lastEquipment != null)
                    {
                        bool looking = true;

                        // parse last equipment records id
                        if (lastEquipment.EquipmentCode.StartsWith(ownerCode))
                        {
                            string temp      = lastEquipment.EquipmentCode.Replace(ownerCode, "");
                            bool   isNumeric = int.TryParse(temp, out int lastEquipmentNumber);
                            if (isNumeric)
                            {
                                equipmentNumber = lastEquipmentNumber + 1;
                            }
                        }
                        else
                        {
                            char[] testChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                            int    index     = lastEquipment.EquipmentCode.IndexOfAny(testChars);

                            if (index >= 0 && lastEquipment.EquipmentCode.Length > index)
                            {
                                string temp = lastEquipment.EquipmentCode.Substring(index,
                                                                                    lastEquipment.EquipmentCode.Length - index);
                                bool isNumeric = int.TryParse(temp, out int lastEquipmentNumber);
                                if (isNumeric)
                                {
                                    equipmentNumber = lastEquipmentNumber + 1;
                                }

                                ownerCode = lastEquipment.EquipmentCode.Substring(0, index);
                            }
                        }

                        // generate a unique equipment number
                        while (looking)
                        {
                            string candidate = GenerateEquipmentCode(ownerCode, equipmentNumber);

                            if ((owner.HetEquipment).Any(x => x.EquipmentCode == candidate))
                            {
                                equipmentNumber++;
                            }
                            else
                            {
                                looking = false;
                            }
                        }
                    }
                }

                // return the new equipment code
                return(GenerateEquipmentCode(ownerCode, equipmentNumber));
            }

            return(null);
        }
Beispiel #13
0
        /// <summary>
        /// Convert to Equipment Lite Model
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="scoringRules"></param>
        /// <param name="agreementStatusId"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static EquipmentLite ToLiteModel(HetEquipment equipment, SeniorityScoringRules scoringRules,
                                                int agreementStatusId, DbAppContext context)
        {
            EquipmentLite equipmentLite = new EquipmentLite();

            if (equipment != null)
            {
                // HETS - 709 [BVT - Adjust the search for Equipment search screen]

                /*
                 * int numberOfBlocks = 0;
                 *
                 * // get number of blocks for this equipment type
                 * if (equipment.DistrictEquipmentType != null)
                 * {
                 *  numberOfBlocks = equipment.DistrictEquipmentType.EquipmentType.IsDumpTruck
                 *      ? scoringRules.GetTotalBlocks("DumpTruck") + 1
                 *      : scoringRules.GetTotalBlocks() + 1;
                 * }
                 *
                 * // get equipment seniority
                 * float seniority = 0F;
                 * if (equipment.Seniority != null)
                 * {
                 *  seniority = (float)equipment.Seniority;
                 * }
                 *
                 * // get equipment block number
                 * int blockNumber = 0;
                 * if (equipment.BlockNumber != null)
                 * {
                 *  blockNumber = (int)equipment.BlockNumber;
                 * }
                 *
                 * // get equipment block number
                 * int numberInBlock = 0;
                 * if (equipment.NumberInBlock != null)
                 * {
                 *  numberInBlock = (int)equipment.NumberInBlock;
                 * }
                 */

                // map data to light model
                equipmentLite.Id = equipment.EquipmentId;

                if (equipment.DistrictEquipmentType != null)
                {
                    equipmentLite.EquipmentType = equipment.DistrictEquipmentType.DistrictEquipmentName;
                }

                if (equipment.Owner != null)
                {
                    equipmentLite.OwnerName = equipment.Owner.OrganizationName;
                    equipmentLite.OwnerId   = equipment.OwnerId;
                }

                // HETS - 709 [BVT - Adjust the search for Equipment search screen]
                //equipmentLite.SeniorityString = FormatSeniorityString(seniority, blockNumber, numberOfBlocks);
                equipmentLite.SeniorityString = "0";

                // HETS - 709 [BVT - Adjust the search for Equipment search screen]
                //equipmentLite.IsHired = CheckIsHired(equipment.HetRentalAgreement.ToList());
                equipmentLite.IsHired = false;

                // HETS - 709 [BVT - Adjust the search for Equipment search screen]
                //equipmentLite.SenioritySortOrder = CalculateSenioritySortOrder(blockNumber, numberInBlock);
                equipmentLite.SenioritySortOrder = 0;

                equipmentLite.Make            = equipment.Make;
                equipmentLite.Model           = equipment.Model;
                equipmentLite.Size            = equipment.Size;
                equipmentLite.Year            = equipment.Year;
                equipmentLite.EquipmentCode   = equipment.EquipmentCode;
                equipmentLite.EquipmentPrefix = Regex.Match(equipment.EquipmentCode, @"^[^\d-]+").Value;

                string temp = "";

                if (!string.IsNullOrEmpty(equipmentLite.EquipmentPrefix))
                {
                    temp = equipment.EquipmentCode.Replace(equipmentLite.EquipmentPrefix, "");
                }

                temp = temp.Replace("-", "");

                equipmentLite.EquipmentNumber = !string.IsNullOrEmpty(temp) ?
                                                int.Parse(Regex.Match(temp, @"\d+").Value) :
                                                0;

                equipmentLite.AttachmentCount  = CalculateAttachmentCount(equipment.HetEquipmentAttachment.ToList());
                equipmentLite.LastVerifiedDate = equipment.LastVerifiedDate;
                equipmentLite.Status           = equipment.EquipmentStatusType.EquipmentStatusTypeCode;
                equipmentLite.LocalArea        = equipment.LocalArea.Name;

                // get project
                HetRentalAgreement agreement = context.HetRentalAgreement
                                               .AsNoTracking()
                                               .Include(x => x.Project)
                                               .Include(x => x.Equipment)
                                               .FirstOrDefault(x => x.RentalAgreementStatusTypeId == agreementStatusId &&
                                                               x.EquipmentId == equipmentLite.Id);

                if (agreement?.Project != null)
                {
                    equipmentLite.ProjectId   = agreement.Project.ProjectId;
                    equipmentLite.ProjectName = agreement.Project.Name;
                }
            }

            return(equipmentLite);
        }
Beispiel #14
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;
            }
        }
Beispiel #15
0
        /// <summary>
        /// Import Equipment
        /// </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 maxEquipmentIndex = 0;

            if (dbContext.HetEquipment.Any())
            {
                maxEquipmentIndex = dbContext.HetEquipment.Max(x => x.EquipmentId);
            }

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

                int ii = startPoint;

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

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

                foreach (ImportModels.Equip 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_Id.ToString());

                    // new entry
                    if (importMap == null && item.Equip_Id > 0)
                    {
                        HetEquipment instance = null;
                        CopyToInstance(dbContext, item, ref instance, systemId, ref maxEquipmentIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, item.Equip_Id.ToString(), NewTable, instance.EquipmentId);
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    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 (EquipmentIndex: {0}): {1}", maxEquipmentIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
        /// <summary>
        /// Seniority List view model
        /// </summary>
        /// <param name="model"></param>
        /// <param name="scoringRules"></param>
        /// <param name="rotationList"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static SeniorityViewModel ToSeniorityViewModel(HetEquipment model, SeniorityScoringRules scoringRules,
                                                              HetRentalRequestRotationList rotationList, DbAppContext context)
        {
            SeniorityViewModel seniorityViewModel = new SeniorityViewModel();

            if (model == null)
            {
                return(seniorityViewModel);
            }

            int numberOfBlocks = 0;

            // get number of blocks for this equipment type
            if (model.DistrictEquipmentType != null)
            {
                numberOfBlocks = model.DistrictEquipmentType.EquipmentType.IsDumpTruck
                    ? scoringRules.GetTotalBlocks("DumpTruck") + 1
                    : scoringRules.GetTotalBlocks() + 1;
            }

            // get equipment block number
            int blockNumber = 0;

            if (model.BlockNumber != null)
            {
                blockNumber = (int)model.BlockNumber;
            }

            // get equipment block number
            int numberInBlock = 0;

            if (model.NumberInBlock != null)
            {
                numberInBlock = (int)model.NumberInBlock;
            }

            // *************************************************************
            // check if this record/owner was called last
            // *************************************************************
            bool callLast = rotationList != null && rotationList.EquipmentId == model.EquipmentId;

            seniorityViewModel.LastCalled = callLast ? "Y" : " ";

            // *************************************************************
            // map data to view model
            // *************************************************************
            seniorityViewModel.Id = model.EquipmentId;

            if (model.DistrictEquipmentType != null)
            {
                seniorityViewModel.EquipmentType = model.DistrictEquipmentType.DistrictEquipmentName;
            }

            if (model.Owner != null)
            {
                seniorityViewModel.OwnerName = model.Owner.OrganizationName;
                seniorityViewModel.OwnerId   = model.OwnerId;
            }

            // replacing Open with 3 (HETS-968 Rotation list -Wrong Block number for Open block)
            seniorityViewModel.Block = blockNumber == numberOfBlocks ? "3" : blockNumber.ToString();

            // format the seniority value
            seniorityViewModel.Seniority = $"{model.Seniority:0.###}";

            // format year / make / model / size
            seniorityViewModel.YearMakeModelSize = $"{model.Year}/{model.Make}/{model.Model}/{model.Size}";

            seniorityViewModel.EquipmentCode = model.EquipmentCode;

            seniorityViewModel.YearsRegistered = model.YearsOfService.ToString();

            // Determine if this equipment is currently hired
            seniorityViewModel.IsHired = EquipmentHelper.IsHired(model.EquipmentId, context) ? "Y" : "N";

            // calculate and format the ytd hours
            float tempHours = EquipmentHelper.GetYtdServiceHours(model.EquipmentId, context);

            seniorityViewModel.YtdHours = string.Format("{0:0.###}", tempHours);

            // format the hours
            seniorityViewModel.HoursYearMinus1 = string.Format("{0:0.###}", model.ServiceHoursLastYear);
            seniorityViewModel.HoursYearMinus2 = string.Format("{0:0.###}", model.ServiceHoursTwoYearsAgo);
            seniorityViewModel.HoursYearMinus3 = string.Format("{0:0.###}", model.ServiceHoursThreeYearsAgo);

            // add the correct sorting order (numeric)
            seniorityViewModel.SenioritySortOrder = EquipmentHelper.CalculateSenioritySortOrder(blockNumber, numberInBlock);

            return(seniorityViewModel);
        }
Beispiel #17
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.DumpTruck oldObject, string systemId)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                // dump truck records update the equipment record
                // find the original equipment record
                string tempId = oldObject.Equip_Id.ToString();

                HetImportMap map = dbContext.HetImportMap
                                   .FirstOrDefault(x => x.OldKey == tempId &&
                                                   x.OldTable == ImportEquip.OldTable &&
                                                   x.NewTable == ImportEquip.NewTable);

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

                // ************************************************
                // get the equipment record and update
                // ************************************************
                HetEquipment equipment = dbContext.HetEquipment.FirstOrDefault(x => x.EquipmentId == map.NewKey);

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

                // set dump truck attributes
                string tempLicensedGvw = ImportUtility.CleanString(oldObject.Licenced_GVW);
                if (!string.IsNullOrEmpty(tempLicensedGvw))
                {
                    equipment.LicencedGvw = tempLicensedGvw;
                }

                string tempLegalCapacity = ImportUtility.CleanString(oldObject.Legal_Capacity);
                if (!string.IsNullOrEmpty(tempLegalCapacity))
                {
                    equipment.LegalCapacity = tempLegalCapacity;
                }

                string tempPupLegalCapacity = ImportUtility.CleanString(oldObject.Legal_PUP_Tare_Weight);

                if (!string.IsNullOrEmpty(tempPupLegalCapacity))
                {
                    equipment.PupLegalCapacity = tempPupLegalCapacity;
                }

                equipment.AppLastUpdateUserid    = systemId;
                equipment.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.HetEquipment.Update(equipment);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - (Old) Equipment Id: " + oldObject.Equip_Id);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #18
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);
        }
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="rotationDoc"></param>
        /// <param name="systemId"></param>
        /// <param name="maxIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.RotationDoc oldObject,
                                           ref BcbidRotationDoc rotationDoc, string systemId, ref int maxIndex)
        {
            try
            {
                if (rotationDoc != null)
                {
                    return;
                }

                rotationDoc = new BcbidRotationDoc {
                    NoteId = oldObject.Note_Id
                };
                ++maxIndex;

                // ***********************************************
                // we only need records from the current fiscal
                // so ignore all others
                // ***********************************************
                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);
                }

                // ***********************************************
                // set rotation data
                // ***********************************************
                string noteType = oldObject.Note_Type;

                if (string.IsNullOrEmpty(noteType))
                {
                    return;
                }

                rotationDoc.NoteType = noteType.Trim();

                // reason
                string reason = oldObject.Reason;

                if (!string.IsNullOrEmpty(reason))
                {
                    rotationDoc.Reason = reason;
                }

                // asked date
                DateTime?createdDate = ImportUtility.CleanDate(oldObject.Created_Dt);

                if (createdDate == null ||
                    createdDate < fiscalStart)
                {
                    return; // move to next
                }

                rotationDoc.AskedDate = (DateTime)createdDate;


                // was asked -- ForceHire
                if (noteType.ToUpper() == "FORCEHIRE")
                {
                    rotationDoc.WasAsked    = false;
                    rotationDoc.IsForceHire = true;
                }
                else
                {
                    rotationDoc.WasAsked    = true;
                    rotationDoc.IsForceHire = false;
                }

                // setup the reason
                string tempResponse = "";

                if (noteType.ToUpper() == "FORCEHIRE")
                {
                    tempResponse = "Force Hire";
                }
                else if (noteType.ToUpper() == "NOHIRE")
                {
                    tempResponse = "No Hire";
                }
                else
                {
                    switch (noteType.ToUpper())
                    {
                    case "0":
                        tempResponse = "Owner didn't call back/no answer";
                        break;

                    case "1":
                        tempResponse = "Equipment not suitable";
                        break;

                    case "2":
                        tempResponse = "Working elsewhere";
                        break;

                    case "3":
                        tempResponse = "No agreement on rates";
                        break;

                    case "4":
                        tempResponse = "Equipment under repairs";
                        break;

                    case "5":
                        tempResponse = "Work limit reached";
                        break;

                    case "6":
                        tempResponse = "No WCB/WCB in arrears";
                        break;

                    case "7":
                        tempResponse = "No insurance/inadequate insurance";
                        break;

                    case "8":
                        tempResponse = "Not interested/turned job down";
                        break;

                    case "9":
                        tempResponse = "Equipment not available";
                        break;

                    case "10":
                        tempResponse = "Other";
                        break;
                    }
                }

                if (string.IsNullOrEmpty(tempResponse))
                {
                    tempResponse = noteType;
                }

                rotationDoc.OfferRefusalReason = tempResponse;

                // ************************************************
                // get the imported equipment record map
                // ************************************************
                string tempId = oldObject.Equip_Id.ToString();

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

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

                // ***********************************************
                // find the equipment record
                // ***********************************************
                HetEquipment equipment = dbContext.HetEquipment.AsNoTracking()
                                         .Include(x => x.LocalArea)
                                         .ThenInclude(y => y.ServiceArea)
                                         .ThenInclude(z => z.District)
                                         .FirstOrDefault(x => x.EquipmentId == mapEquip.NewKey);

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

                int tempNewEquipmentId = equipment.EquipmentId;
                rotationDoc.EquipmentId = tempNewEquipmentId;

                // ************************************************
                // get the imported project record map
                // ************************************************
                string tempProjectId = oldObject.Project_Id.ToString();

                HetImportMap mapProject = dbContext.HetImportMap.AsNoTracking()
                                          .FirstOrDefault(x => x.OldKey == tempProjectId &&
                                                          x.OldTable == ImportProject.OldTable &&
                                                          x.NewTable == ImportProject.NewTable);

                // ***********************************************
                // find the project record
                // ***********************************************
                HetProject project;

                if (mapProject != null)
                {
                    project = dbContext.HetProject.AsNoTracking()
                              .FirstOrDefault(x => x.ProjectId == mapProject.NewKey);

                    if (project == null)
                    {
                        throw new ArgumentException(string.Format("Cannot locate Project record (Rotation Doc Id: {0}", tempId));
                    }

                    int tempNewProjectId = project.ProjectId;
                    rotationDoc.ProjectId = tempNewProjectId;
                }
                else
                {
                    int districtId = equipment.LocalArea.ServiceArea.District.DistrictId;

                    int?statusId = StatusHelper.GetStatusId(HetProject.StatusComplete, "projectStatus", dbContext);
                    if (statusId == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (Time Sheet Equip Id: {0}", tempId));
                    }

                    // create new project
                    project = new HetProject
                    {
                        DistrictId          = districtId,
                        Information         = "Created to support Rotation Doc import from BCBid",
                        ProjectStatusTypeId = (int)statusId,
                        Name                   = "Legacy BCBid Project",
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    // save now so we can access it for other time records
                    dbContext.HetProject.Add(project);
                    dbContext.SaveChangesForImport();

                    // add mapping record
                    ImportUtility.AddImportMapForProgress(dbContext, ImportProject.OldTable, tempProjectId, project.ProjectId, ImportProject.NewTable);
                    dbContext.SaveChangesForImport();
                }

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

                dbContext.BcbidRotationDoc.Add(rotationDoc);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Master Rotation Doc Index: " + maxIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #20
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="timeRecord"></param>
        /// <param name="systemId"></param>
        /// <param name="maxTimeSheetIndex"></param>
        private static void CopyToTimeRecorded(DbAppContext dbContext, ImportModels.EquipUsage oldObject,
                                               ref HetTimeRecord timeRecord, string systemId, ref int maxTimeSheetIndex)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

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

                // ***********************************************
                // we only need records from the current fiscal
                // so ignore all others
                // ***********************************************
                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);
                }

                string tempRecordDate = oldObject.Worked_Dt;

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

                if (!string.IsNullOrEmpty(tempRecordDate))
                {
                    DateTime?recordDate = ImportUtility.CleanDate(tempRecordDate);

                    if (recordDate == null || recordDate < fiscalStart)
                    {
                        return; // ignore this record - it is outside of the fiscal years
                    }
                }

                // ************************************************
                // get the imported equipment record map
                // ************************************************
                string tempId = oldObject.Equip_Id.ToString();

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

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

                // ***********************************************
                // find the equipment record
                // ***********************************************
                HetEquipment equipment = dbContext.HetEquipment.AsNoTracking()
                                         .Include(x => x.LocalArea)
                                         .ThenInclude(y => y.ServiceArea)
                                         .ThenInclude(z => z.District)
                                         .FirstOrDefault(x => x.EquipmentId == mapEquip.NewKey);

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

                // ************************************************
                // get the imported project record map
                // ************************************************
                string tempProjectId = oldObject.Project_Id.ToString();

                HetImportMap mapProject = dbContext.HetImportMap.AsNoTracking()
                                          .FirstOrDefault(x => x.OldKey == tempProjectId &&
                                                          x.OldTable == ImportProject.OldTable &&
                                                          x.NewTable == ImportProject.NewTable);

                // ***********************************************
                // find the project record
                // (or create a project (inactive))
                // ***********************************************
                HetProject project;

                if (mapProject != null)
                {
                    project = dbContext.HetProject.AsNoTracking()
                              .FirstOrDefault(x => x.ProjectId == mapProject.NewKey);

                    if (project == null)
                    {
                        throw new ArgumentException(string.Format("Cannot locate Project record (Time Sheet Equip Id: {0}", tempId));
                    }
                }
                else
                {
                    int districtId = equipment.LocalArea.ServiceArea.District.DistrictId;

                    int?statusId = StatusHelper.GetStatusId(HetProject.StatusComplete, "projectStatus", dbContext);
                    if (statusId == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (Time Sheet Equip Id: {0}", tempId));
                    }

                    // create new project
                    project = new HetProject
                    {
                        DistrictId          = districtId,
                        Information         = "Created to support Time Record import from BCBid",
                        ProjectStatusTypeId = (int)statusId,
                        Name                   = "Legacy BCBid Project",
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    // save now so we can access it for other time records
                    dbContext.HetProject.Add(project);
                    dbContext.SaveChangesForImport();

                    // add mapping record
                    ImportUtility.AddImportMapForProgress(dbContext, ImportProject.OldTable, tempProjectId, project.ProjectId, ImportProject.NewTable);
                    dbContext.SaveChangesForImport();
                }

                // ***********************************************
                // find or create the rental agreement
                // ***********************************************
                DateTime?enteredDate = ImportUtility.CleanDate(oldObject.Entered_Dt);  // use for the agreement

                HetRentalAgreement agreement = dbContext.HetRentalAgreement.AsNoTracking()
                                               .FirstOrDefault(x => x.EquipmentId == equipment.EquipmentId &&
                                                               x.ProjectId == project.ProjectId &&
                                                               x.DistrictId == equipment.LocalArea.ServiceArea.District.DistrictId);

                if (agreement == null)
                {
                    int equipmentId = equipment.EquipmentId;
                    int projectId   = project.ProjectId;
                    int districtId  = equipment.LocalArea.ServiceArea.District.DistrictId;

                    int?statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusComplete, "rentalAgreementStatus", dbContext);
                    if (statusId == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (Time Sheet Equip Id: {0}", tempId));
                    }

                    int?agrRateTypeId = StatusHelper.GetRatePeriodId(HetRatePeriodType.PeriodDaily, dbContext);
                    if (agrRateTypeId == null)
                    {
                        throw new DataException("Rate Period Id cannot be null");
                    }

                    int?year = (ImportUtility.CleanDate(oldObject.Worked_Dt))?.Year;

                    // create a new agreement record
                    agreement = new HetRentalAgreement
                    {
                        EquipmentId = equipmentId,
                        ProjectId   = projectId,
                        DistrictId  = districtId,
                        RentalAgreementStatusTypeId = (int)statusId,
                        RatePeriodTypeId            = (int)agrRateTypeId,
                        Note                   = "Created to support Time Record import from BCBid",
                        Number                 = string.Format("BCBid{0}-{1}-{2}", projectId, equipmentId, year),
                        DatedOn                = enteredDate,
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    // save now so we can access it for other time records
                    dbContext.HetRentalAgreement.Add(agreement);
                    dbContext.SaveChangesForImport();
                }

                // ***********************************************
                // create time record
                // ***********************************************
                timeRecord = new HetTimeRecord {
                    TimeRecordId = ++maxTimeSheetIndex
                };

                // ***********************************************
                // set time period type
                // ***********************************************
                int?timePeriodTypeId = StatusHelper.GetTimePeriodId(HetTimePeriodType.PeriodDay, dbContext);
                if (timePeriodTypeId == null)
                {
                    throw new DataException("Time Period Id cannot be null");
                }

                timeRecord.TimePeriodTypeId = (int)timePeriodTypeId;

                // ***********************************************
                // set time record attributes
                // ***********************************************
                DateTime?workedDate = ImportUtility.CleanDate(oldObject.Worked_Dt);

                if (workedDate != null)
                {
                    timeRecord.WorkedDate = (DateTime)workedDate;
                }
                else
                {
                    throw new DataException(string.Format("Worked Date cannot be null (TimeSheet Index: {0}", maxTimeSheetIndex));
                }

                // get hours worked
                float?tempHoursWorked = ImportUtility.GetFloatValue(oldObject.Hours);

                if (tempHoursWorked != null)
                {
                    timeRecord.Hours = tempHoursWorked;
                }
                else
                {
                    throw new DataException(string.Format("Hours cannot be null (TimeSheet Index: {0}", maxTimeSheetIndex));
                }

                if (enteredDate != null)
                {
                    timeRecord.EnteredDate = (DateTime)enteredDate;
                }
                else
                {
                    throw new DataException(string.Format("Entered Date cannot be null (TimeSheet Index: {0}", maxTimeSheetIndex));
                }

                // ***********************************************
                // create time record
                // ***********************************************
                int raId = agreement.RentalAgreementId;

                timeRecord.RentalAgreementId      = raId;
                timeRecord.AppCreateUserid        = systemId;
                timeRecord.AppCreateTimestamp     = DateTime.UtcNow;
                timeRecord.AppLastUpdateUserid    = systemId;
                timeRecord.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.HetTimeRecord.Add(timeRecord);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Worked Date: " + oldObject.Worked_Dt);
                Debug.WriteLine("***Error*** - Master Time Record Index: " + maxTimeSheetIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #21
0
        /// <summary>
        /// Create Last Called
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="systemId"></param>
        public static void ProcessLastCalled(PerformContext performContext, DbAppContext dbContext, string systemId)
        {
            try
            {
                performContext.WriteLine("*** Recreating Last Called ***");
                Debug.WriteLine("Recreating Last Called");

                int    ii = 0;
                string _oldTableProgress = "LastCalled_Progress";
                string _newTable         = "LastCalled";

                // check if the last called has already been completed
                int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, _oldTableProgress, BcBidImport.SigId, _newTable);

                if (startPoint == BcBidImport.SigId)    // this means the assignment job is complete
                {
                    performContext.WriteLine("*** Recreating Last Called is complete from the former process ***");
                    return;
                }

                // ************************************************************
                // get all last called records
                // ************************************************************
                List <HetLocalAreaRotationList> rotationList = dbContext.HetLocalAreaRotationList.AsNoTracking()
                                                               .Distinct()
                                                               .ToList();

                // ************************************************************************
                // iterate the data and create rotation requests
                // ************************************************************************
                Debug.WriteLine("Recreating Last Called - Rotation List Record Count: " + rotationList.Count);

                // get status
                int?statusIdComplete = StatusHelper.GetStatusId(HetRentalRequest.StatusComplete, "rentalRequestStatus", dbContext);

                if (statusIdComplete == null)
                {
                    throw new DataException("Status Id cannot be null");
                }

                foreach (HetLocalAreaRotationList listItem in rotationList)
                {
                    HetRentalRequest request = new HetRentalRequest
                    {
                        LocalAreaId               = listItem.LocalAreaId,
                        DistrictEquipmentTypeId   = listItem.DistrictEquipmentTypeId,
                        RentalRequestStatusTypeId = (int)statusIdComplete,
                        ExpectedStartDate         = DateTime.Now,
                        ExpectedEndDate           = DateTime.Now,
                        EquipmentCount            = 1,
                        ExpectedHours             = 0,
                        AppCreateUserid           = systemId,
                        AppCreateTimestamp        = DateTime.UtcNow,
                        AppLastUpdateUserid       = systemId,
                        AppLastUpdateTimestamp    = DateTime.UtcNow
                    };

                    dbContext.HetRentalRequest.Add(request);

                    // save change to database
                    if (ii++ % 100 == 0)
                    {
                        Debug.WriteLine("Recreating Last Called - Index: " + ii);
                        ImportUtility.AddImportMapForProgress(dbContext, _oldTableProgress, ii.ToString(), BcBidImport.SigId, _newTable);
                        dbContext.SaveChangesForImport();
                    }
                }

                // save remaining requests
                dbContext.SaveChangesForImport();

                // ************************************************************************
                // iterate the data and create "last called" records
                // ************************************************************************
                foreach (HetLocalAreaRotationList listItem in rotationList)
                {
                    // get request
                    HetRentalRequest request = dbContext.HetRentalRequest.AsNoTracking()
                                               .FirstOrDefault(x => x.LocalAreaId == listItem.LocalAreaId &&
                                                               x.DistrictEquipmentTypeId == listItem.DistrictEquipmentTypeId);

                    if (request == null)
                    {
                        throw new DataException("Rental request cannot be null");
                    }

                    // block 1
                    if (listItem.AskNextBlock1Id != null)
                    {
                        // create last call record
                        HetRentalRequestRotationList rotation = new HetRentalRequestRotationList
                        {
                            RentalRequestId       = request.RentalRequestId,
                            EquipmentId           = listItem.AskNextBlock1Id,
                            BlockNumber           = 1,
                            RotationListSortOrder = 1,
                            AskedDateTime         = DateTime.Now,
                            WasAsked              = true,
                            OfferResponse         = "Yes",
                            OfferResponseDatetime = DateTime.Now,
                            IsForceHire           = false,
                            Note                   = "CONVERSION",
                            AppCreateUserid        = systemId,
                            AppCreateTimestamp     = DateTime.UtcNow,
                            AppLastUpdateUserid    = systemId,
                            AppLastUpdateTimestamp = DateTime.UtcNow
                        };

                        dbContext.HetRentalRequestRotationList.Add(rotation);
                    }

                    // block 2
                    if (listItem.AskNextBlock2Id != null)
                    {
                        // create last call record
                        HetRentalRequestRotationList rotation = new HetRentalRequestRotationList
                        {
                            RentalRequestId       = request.RentalRequestId,
                            EquipmentId           = listItem.AskNextBlock2Id,
                            BlockNumber           = 2,
                            RotationListSortOrder = 2,
                            AskedDateTime         = DateTime.Now,
                            WasAsked              = true,
                            OfferResponse         = "Yes",
                            OfferResponseDatetime = DateTime.Now,
                            IsForceHire           = false,
                            Note                   = "CONVERSION",
                            AppCreateUserid        = systemId,
                            AppCreateTimestamp     = DateTime.UtcNow,
                            AppLastUpdateUserid    = systemId,
                            AppLastUpdateTimestamp = DateTime.UtcNow
                        };

                        dbContext.HetRentalRequestRotationList.Add(rotation);
                    }

                    // open block
                    if (listItem.AskNextBlockOpenId != null)
                    {
                        // get equipment record
                        HetEquipment equipment = dbContext.HetEquipment.AsNoTracking()
                                                 .FirstOrDefault(x => x.EquipmentId == listItem.AskNextBlockOpenId);

                        if (equipment == null)
                        {
                            throw new DataException("Equipment cannot be null");
                        }

                        // create last call record
                        HetRentalRequestRotationList rotation = new HetRentalRequestRotationList
                        {
                            RentalRequestId       = request.RentalRequestId,
                            EquipmentId           = listItem.AskNextBlockOpenId,
                            BlockNumber           = equipment.BlockNumber,
                            RotationListSortOrder = 3,
                            AskedDateTime         = DateTime.Now,
                            WasAsked              = true,
                            OfferResponse         = "Yes",
                            OfferResponseDatetime = DateTime.Now,
                            IsForceHire           = false,
                            Note                   = "CONVERSION",
                            AppCreateUserid        = systemId,
                            AppCreateTimestamp     = DateTime.UtcNow,
                            AppLastUpdateUserid    = systemId,
                            AppLastUpdateTimestamp = DateTime.UtcNow
                        };

                        dbContext.HetRentalRequestRotationList.Add(rotation);
                    }

                    // save change to database
                    if (ii++ % 100 == 0)
                    {
                        Debug.WriteLine("Recreating Last Called - Index: " + ii);
                        ImportUtility.AddImportMapForProgress(dbContext, _oldTableProgress, ii.ToString(), BcBidImport.SigId, _newTable);
                        dbContext.SaveChangesForImport();
                    }
                }

                // save remaining requests
                dbContext.SaveChangesForImport();

                // ************************************************************
                // save final set of updates
                // ************************************************************
                try
                {
                    performContext.WriteLine("*** Recreating Last Called is Done ***");
                    Debug.WriteLine("Recreating Last Called is Done");
                    ImportUtility.AddImportMapForProgress(dbContext, _oldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, _newTable);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    string temp = string.Format("Error saving data (Record: {0}): {1}", ii, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
        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)));
        }