Beispiel #1
0
        private bool CanAccessOwner(int businessId, int ownerId)
        {
            // validate that the current user can access this record
            string userId     = UserAccountHelper.GetUserId(_httpContext);
            bool   isBusiness = UserAccountHelper.IsBusiness(_httpContext);

            // not a business user
            if (string.IsNullOrEmpty(userId) || !isBusiness)
            {
                return(false);
            }

            // get business & owner record
            HetOwner owner = _context.HetOwner.AsNoTracking()
                             .Include(x => x.Business)
                             .ThenInclude(x => x.HetBusinessUser)
                             .FirstOrDefault(x => x.BusinessId == businessId &&
                                             x.OwnerId == ownerId);

            // get user
            HetBusinessUser user = owner?.Business?.HetBusinessUser
                                   .FirstOrDefault(x => x.BceidUserId.Equals(userId, StringComparison.InvariantCultureIgnoreCase));

            // no access to business or business doesn't exist
            return(user != null);
        }
Beispiel #2
0
        private static TableCell SetupCell(HetOwner owner, double widthInCm, double start)
        {
            try
            {
                var tableCell = new TableCell();

                var tableCellProperties = new TableCellProperties();
                tableCellProperties.AppendChild(new TableCellWidth {
                    Width = CentimeterToDxa(widthInCm).ToString(), Type = TableWidthUnitValues.Dxa
                });
                tableCellProperties.AppendChild(new TableCellVerticalAlignment()
                {
                    Val = TableVerticalAlignmentValues.Center
                });
                tableCell.AppendChild(tableCellProperties);

                var paragraphProperties = new ParagraphProperties();

                var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
                paragraphMarkRunProperties.AppendChild(new Color {
                    Val = "000000"
                });
                paragraphMarkRunProperties.AppendChild(new RunFonts {
                    Ascii = "Arial"
                });
                paragraphMarkRunProperties.AppendChild(new FontSize()
                {
                    Val = "13pt"
                });
                paragraphProperties.AppendChild(paragraphMarkRunProperties);

                paragraphProperties.AppendChild(new Justification {
                    Val = JustificationValues.Left
                });
                paragraphProperties.AppendChild(new Indentation {
                    Start = CentimeterToDxa(start).ToString()
                });

                var paragraph = new Paragraph();
                paragraph.AppendChild(paragraphProperties);

                if (owner != null)
                {
                    PopulateParagraph(owner, paragraph);
                }

                tableCell.AppendChild(paragraph);

                return(tableCell);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Convert to Owner Lite Model
        /// </summary>
        /// <param name="owner"></param>
        public static OwnerLite ToLiteModel(HetOwner owner)
        {
            OwnerLite ownerLite = new OwnerLite();

            if (owner != null)
            {
                ownerLite.Id               = owner.OwnerId;
                ownerLite.OwnerCode        = owner.OwnerCode;
                ownerLite.OrganizationName = owner.OrganizationName;

                if (owner.LocalArea != null)
                {
                    ownerLite.LocalAreaName = owner.LocalArea.Name;
                }

                if (owner.PrimaryContact != null)
                {
                    string tempName = "";

                    if (!string.IsNullOrEmpty(owner.PrimaryContact.GivenName))
                    {
                        tempName = owner.PrimaryContact.GivenName.Trim();

                        if (!string.IsNullOrEmpty(tempName))
                        {
                            tempName = tempName + " ";
                        }
                    }

                    if (!string.IsNullOrEmpty(owner.PrimaryContact.Surname))
                    {
                        tempName = tempName + owner.PrimaryContact.Surname.Trim();
                    }

                    ownerLite.PrimaryContactName = tempName;

                    // set phone number
                    ownerLite.PrimaryContactNumber = owner.PrimaryContact.WorkPhoneNumber;

                    if (string.IsNullOrEmpty(ownerLite.PrimaryContactNumber))
                    {
                        ownerLite.PrimaryContactNumber = owner.PrimaryContact.MobilePhoneNumber;
                    }
                }

                if (owner.HetEquipment != null)
                {
                    ownerLite.EquipmentCount = CalculateEquipmentCount(owner.HetEquipment.ToList());
                }

                ownerLite.Status = owner.OwnerStatusType.Description;
            }

            return(ownerLite);
        }
        public virtual IActionResult OwnerIdAttachmentsPost([FromRoute] int id, [FromForm] IList <IFormFile> files)
        {
            // validate the id
            bool exists = _context.HetOwner.Any(a => a.OwnerId == id);

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

            HetOwner owner = _context.HetOwner
                             .Include(x => x.HetDigitalFile)
                             .First(a => a.OwnerId == 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;

                    owner.HetDigitalFile.Add(attachment);
                }
            }

            _context.SaveChanges();

            return(new ObjectResult(owner.HetDigitalFile));
        }
Beispiel #5
0
        /// <summary>
        /// Get an Owner record
        /// </summary>
        /// <param name="id"></param>
        /// <param name="context"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static HetOwner GetRecord(int id, DbAppContext context, IConfiguration configuration)
        {
            // get equipment status types
            int?statusIdArchived = StatusHelper.GetStatusId(HetEquipment.StatusArchived, "equipmentStatus", context);

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

            // get owner record
            HetOwner owner = context.HetOwner.AsNoTracking()
                             .Include(x => x.OwnerStatusType)
                             .Include(x => x.LocalArea.ServiceArea.District.Region)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.LocalArea.ServiceArea.District.Region)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.DistrictEquipmentType)
                             .ThenInclude(z => z.EquipmentType)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.Owner)
                             .ThenInclude(c => c.PrimaryContact)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.EquipmentStatusType)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.HetEquipmentAttachment)
                             .Include(x => x.HetContact)
                             .Include(x => x.PrimaryContact)
                             .FirstOrDefault(a => a.OwnerId == id);

            if (owner != null)
            {
                // remove any archived equipment
                owner.HetEquipment = owner.HetEquipment.Where(e => e.EquipmentStatusTypeId != statusIdArchived).ToList();

                // populate the "Status" description
                owner.Status = owner.OwnerStatusType.OwnerStatusTypeCode;

                foreach (HetEquipment equipment in owner.HetEquipment)
                {
                    equipment.IsHired         = EquipmentHelper.IsHired(id, context);
                    equipment.NumberOfBlocks  = EquipmentHelper.GetNumberOfBlocks(equipment, configuration);
                    equipment.HoursYtd        = EquipmentHelper.GetYtdServiceHours(id, context);
                    equipment.Status          = equipment.EquipmentStatusType.EquipmentStatusTypeCode;
                    equipment.EquipmentNumber = int.Parse(Regex.Match(equipment.EquipmentCode, @"\d+").Value);
                }

                // HETS-1115 - Do not allow changing seniority affecting entities if an active request exists
                owner.ActiveRentalRequest = RentalRequestStatus(id, context);
            }

            return(owner);
        }
Beispiel #6
0
        private static void PopulateParagraph(HetOwner owner, Paragraph paragraph)
        {
            paragraph.AppendChild(new Text(owner.OrganizationName.Trim()));
            paragraph.AppendChild(new Break());
            paragraph.AppendChild(new Text(owner.Address1.Trim()));
            paragraph.AppendChild(new Break());

            if (!string.IsNullOrWhiteSpace(owner.Address2))
            {
                paragraph.AppendChild(new Text(owner.Address2.Trim()));
                paragraph.AppendChild(new Text(", "));
            }

            paragraph.AppendChild(new Text($"{owner.City.Trim()}, {owner.Province.Trim()} {owner.PostalCode.Trim()}"));
        }
Beispiel #7
0
        /// <summary>
        /// Get an Owner record
        /// </summary>
        /// <param name="id"></param>
        /// <param name="context"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static HetOwner GetRecord(int id, DbAppContext context, IConfiguration configuration)
        {
            HetOwner owner = context.HetOwner.AsNoTracking()
                             .Include(x => x.OwnerStatusType)
                             .Include(x => x.LocalArea.ServiceArea.District.Region)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.LocalArea.ServiceArea.District.Region)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.DistrictEquipmentType)
                             .ThenInclude(z => z.EquipmentType)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.Owner)
                             .ThenInclude(c => c.PrimaryContact)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.EquipmentStatusType)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(y => y.HetEquipmentAttachment)
                             .Include(x => x.HetContact)
                             .Include(x => x.PrimaryContact)
                             .FirstOrDefault(a => a.OwnerId == id);

            if (owner != null)
            {
                // remove any archived equipment
                owner.HetEquipment = owner.HetEquipment.Where(e => e.EquipmentStatusType.EquipmentStatusTypeCode != HetEquipment.StatusArchived).ToList();

                // populate the "Status" description
                owner.Status = owner.OwnerStatusType.OwnerStatusTypeCode;

                foreach (HetEquipment equipment in owner.HetEquipment)
                {
                    equipment.IsHired         = EquipmentHelper.IsHired(id, context);
                    equipment.NumberOfBlocks  = EquipmentHelper.GetNumberOfBlocks(equipment, configuration);
                    equipment.HoursYtd        = EquipmentHelper.GetYtdServiceHours(id, context);
                    equipment.Status          = equipment.EquipmentStatusType.EquipmentStatusTypeCode;
                    equipment.EquipmentNumber = int.Parse(Regex.Match(equipment.EquipmentCode, @"\d+").Value);
                }
            }

            return(owner);
        }
Beispiel #8
0
        public static List <History> GetHistoryRecords(int id, int?offset, int?limit, DbAppContext context)
        {
            HetOwner owner = context.HetOwner.AsNoTracking()
                             .Include(x => x.HetHistory)
                             .First(a => a.OwnerId == id);

            List <HetHistory> data = owner.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].OwnerId;
                }

                result.Add(temp);
            }

            return(result);
        }
Beispiel #9
0
        public virtual IActionResult BceidOwnerEquipmentGet([FromRoute] int id)
        {
            // get business
            string businessGuid = UserAccountHelper.GetBusinessGuid(_httpContext, _env);

            HetBusiness business = _context.HetBusiness.AsNoTracking()
                                   .FirstOrDefault(x => x.BceidBusinessGuid.ToLower().Trim() == businessGuid.ToLower().Trim());

            if (business == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }

            // check access
            if (!CanAccessOwner(business.BusinessId, id))
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }

            // retrieve the data and return
            HetOwner owner = _context.HetOwner.AsNoTracking()
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.LocalArea.ServiceArea.District.Region)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.DistrictEquipmentType)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.Owner)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.HetEquipmentAttachment)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.HetNote)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.HetDigitalFile)
                             .Include(x => x.HetEquipment)
                             .ThenInclude(x => x.HetHistory)
                             .First(a => a.OwnerId == id);

            return(new ObjectResult(new HetsResponse(owner.HetEquipment)));
        }
Beispiel #10
0
        /// <summary>
        /// Convert to Owner Wb Cgl Model
        /// </summary>
        /// <param name="owner"></param>
        public static OwnerWcbCgl ToWcbCglModel(HetOwner owner)
        {
            OwnerWcbCgl ownerLite = new OwnerWcbCgl();

            if (owner != null)
            {
                ownerLite.Id               = owner.OwnerId;
                ownerLite.OwnerCode        = owner.OwnerCode;
                ownerLite.OrganizationName = owner.OrganizationName;

                if (owner.LocalArea != null)
                {
                    ownerLite.ServiceAreaId = owner.LocalArea.ServiceArea.ServiceAreaId;
                    ownerLite.LocalAreaName = owner.LocalArea.Name;
                }

                if (owner.PrimaryContact != null)
                {
                    // set phone number
                    ownerLite.PrimaryContactNumber = owner.PrimaryContact.WorkPhoneNumber;

                    if (string.IsNullOrEmpty(ownerLite.PrimaryContactNumber))
                    {
                        ownerLite.PrimaryContactNumber = owner.PrimaryContact.MobilePhoneNumber;
                    }

                    // set mobile number
                    ownerLite.PrimaryContactCell = owner.PrimaryContact.MobilePhoneNumber;
                }

                ownerLite.WcbNumber     = owner.WorkSafeBcpolicyNumber;
                ownerLite.WcbExpiryDate = owner.WorkSafeBcexpiryDate;
                ownerLite.CglNumber     = owner.CglPolicyNumber;
                ownerLite.CglExpiryDate = owner.CglendDate;
            }

            return(ownerLite);
        }
Beispiel #11
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipment"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipmentIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Equip oldObject,
                                           ref HetEquipment equipment, string systemId, ref int maxEquipmentIndex)
        {
            try
            {
                int?statusIdApproved   = StatusHelper.GetStatusId("Approved", "equipmentStatus", dbContext);
                int?statusIdUnapproved = StatusHelper.GetStatusId("Unapproved", "equipmentStatus", dbContext);
                int?statusIdArchived   = StatusHelper.GetStatusId("Archived", "equipmentStatus", dbContext);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    equipment.Size = tempSize;
                }

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

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

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

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

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

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

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

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

                    equipment.HetNote.Add(note);
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                dbContext.HetEquipment.Add(equipment);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Code: " + equipment.EquipmentCode);
                Debug.WriteLine("***Error*** - Master Equipment Index: " + maxEquipmentIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #12
0
        /// <summary>
        /// Annual Rollover
        /// </summary>
        /// <param name="context"></param>
        /// <param name="districtId"></param>
        /// <param name="seniorityScoringRules"></param>
        /// <param name="connectionString"></param>
        public static void AnnualRolloverJob(PerformContext context, int districtId, string seniorityScoringRules, string connectionString)
        {
            try
            {
                // open a connection to the database
                DbAppContext dbContext = new DbAppContext(connectionString);

                // get processing rules
                SeniorityScoringRules scoringRules = new SeniorityScoringRules(seniorityScoringRules);

                // update progress bar
                IProgressBar progress = context.WriteProgressBar();
                context.WriteLine("Starting Annual Rollover Job - District #" + districtId);

                progress.SetValue(0);

                // validate district id
                HetDistrict district = dbContext.HetDistrict.AsNoTracking()
                                       .FirstOrDefault(x => x.DistrictId == districtId);

                if (district == null)
                {
                    context.WriteLine("District not found");
                    progress.SetValue(100);
                    return;
                }

                // get status record - and ensure we're active
                HetDistrictStatus status = GetRecord(districtId, dbContext);

                if (status == null)
                {
                    context.WriteLine("District Status not found");
                    progress.SetValue(100);
                    return;
                }

                // get equipment status
                int?statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", dbContext);
                if (statusId == null)
                {
                    context.WriteLine("Equipment Status not found");
                    progress.SetValue(100);
                    return;
                }

                // determine the "Rollover Date" (required for testing)
                DateTime rolloverDate;

                if (DateTime.UtcNow.Month == 1 || DateTime.UtcNow.Month == 2 || DateTime.UtcNow.Month == 3)
                {
                    if (status.NextFiscalYear == null)
                    {
                        status.NextFiscalYear = DateTime.UtcNow.Year;
                    }

                    rolloverDate = new DateTime((int)status.NextFiscalYear, DateTime.UtcNow.Month, DateTime.UtcNow.Day);
                }
                else
                {
                    if (status.CurrentFiscalYear == null)
                    {
                        status.CurrentFiscalYear = DateTime.UtcNow.Year;
                    }

                    rolloverDate = new DateTime((int)status.CurrentFiscalYear, DateTime.UtcNow.Month, DateTime.UtcNow.Day);
                }

                // get all district equipment types
                List <HetDistrictEquipmentType> equipmentTypes = dbContext.HetDistrictEquipmentType.AsNoTracking()
                                                                 .Include(x => x.EquipmentType)
                                                                 .Where(x => x.DistrictId == districtId).ToList();

                // get all local areas
                List <HetLocalArea> localAreas = dbContext.HetLocalArea.AsNoTracking()
                                                 .Where(a => a.ServiceArea.DistrictId == districtId).ToList();

                // update status - job is kicked off
                int localAreaCompleteCount = 0;
                int equipmentCompleteCount = 0;

                UpdateStatusKickoff(dbContext, status, localAreaCompleteCount, equipmentCompleteCount);

                // process all local areas and equipment types
                foreach (HetLocalArea localArea in localAreas.WithProgress(progress))
                {
                    // re-open the connection
                    dbContext = new DbAppContext(connectionString);

                    if (localArea.Name != null)
                    {
                        context.WriteLine("Local Area: " + localArea.Name);
                    }
                    else
                    {
                        context.WriteLine("Local Area ID: " + localArea.LocalAreaId);
                    }

                    // reset equipment counter
                    equipmentCompleteCount = 0;

                    foreach (HetDistrictEquipmentType equipmentType in equipmentTypes)
                    {
                        // it this a dump truck?
                        bool isDumpTruck = equipmentType.EquipmentType.IsDumpTruck;

                        // get rules for scoring and seniority block
                        int seniorityScoring = isDumpTruck ? scoringRules.GetEquipmentScore("DumpTruck") : scoringRules.GetEquipmentScore();
                        int blockSize        = isDumpTruck ? scoringRules.GetBlockSize("DumpTruck") : scoringRules.GetBlockSize();
                        int totalBlocks      = isDumpTruck ? scoringRules.GetTotalBlocks("DumpTruck") : scoringRules.GetTotalBlocks();

                        using (DbAppContext etContext = new DbAppContext(connectionString))
                        {
                            List <HetEquipment> data = etContext.HetEquipment
                                                       .Include(x => x.LocalArea)
                                                       .Include(x => x.DistrictEquipmentType.EquipmentType)
                                                       .Where(x => x.EquipmentStatusTypeId == statusId &&
                                                              x.LocalAreaId == localArea.LocalAreaId &&
                                                              x.DistrictEquipmentTypeId == equipmentType.DistrictEquipmentTypeId)
                                                       .ToList();

                            foreach (HetEquipment equipment in data)
                            {
                                // rollover the year
                                equipment.ServiceHoursThreeYearsAgo = equipment.ServiceHoursTwoYearsAgo;
                                equipment.ServiceHoursTwoYearsAgo   = equipment.ServiceHoursLastYear;
                                equipment.ServiceHoursLastYear      = EquipmentHelper.GetYtdServiceHours(equipment.EquipmentId, dbContext, rolloverDate);
                                equipment.CalculateYearsOfService(DateTime.UtcNow);

                                // blank out the override reason
                                equipment.SeniorityOverrideReason = "";

                                // update the seniority score
                                equipment.CalculateSeniority(seniorityScoring);

                                etContext.HetEquipment.Update(equipment);
                                etContext.SaveChanges();
                            }
                        }

                        // now update the rotation list
                        using (DbAppContext abContext = new DbAppContext(connectionString))
                        {
                            int localAreaId     = localArea.LocalAreaId;
                            int equipmentTypeId = equipmentType.DistrictEquipmentTypeId;

                            SeniorityListHelper.AssignBlocks(localAreaId, equipmentTypeId, blockSize, totalBlocks, abContext);
                        }

                        // increment counters and update status
                        equipmentCompleteCount++;
                        UpdateStatus(dbContext, status, localAreaCompleteCount, equipmentCompleteCount);
                    }

                    // increment counters and update status
                    localAreaCompleteCount++;
                    UpdateStatus(dbContext, status, localAreaCompleteCount, equipmentCompleteCount);
                    if (status.ProgressPercentage != null)
                    {
                        progress.SetValue((int)status.ProgressPercentage);
                    }
                }

                // done!
                UpdateStatusComplete(dbContext, status, localAreaCompleteCount, equipmentCompleteCount);
                progress.SetValue(100);

                // **********************************************************
                // regenerate Owner Secret Keys for this district
                // **********************************************************
                dbContext = new DbAppContext(connectionString);

                context.WriteLine("");
                context.WriteLine("Generate New Secret Keys - District #" + districtId);
                progress = context.WriteProgressBar();

                progress.SetValue(0);
                // get records
                List <HetOwner> owners = dbContext.HetOwner.AsNoTracking()
                                         .Where(x => x.BusinessId == null &&
                                                x.LocalArea.ServiceArea.DistrictId == districtId)
                                         .ToList();

                int i          = 0;
                int ownerCount = owners.Count;

                foreach (HetOwner owner in owners)
                {
                    i++;
                    string key = SecretKeyHelper.RandomString(8, owner.OwnerId);

                    string temp = owner.OwnerCode;

                    if (string.IsNullOrEmpty(temp))
                    {
                        temp = SecretKeyHelper.RandomString(4, owner.OwnerId);
                    }

                    key = temp + "-" + (rolloverDate.Year + 1) + "-" + key;

                    // get owner and update
                    HetOwner ownerRecord = dbContext.HetOwner.First(x => x.OwnerId == owner.OwnerId);
                    ownerRecord.SharedKey = key;
                    dbContext.HetOwner.Update(ownerRecord);

                    decimal tempProgress = Convert.ToDecimal(i) / Convert.ToDecimal(ownerCount);
                    tempProgress = tempProgress * 100;
                    int percentComplete = Convert.ToInt32(tempProgress);

                    if (percentComplete < 1)
                    {
                        percentComplete = 1;
                    }
                    if (percentComplete > 99)
                    {
                        percentComplete = 100;
                    }

                    progress.SetValue(percentComplete);
                }

                // save remaining updates - done!
                dbContext.SaveChangesForImport();
                progress.SetValue(100);
                context.WriteLine("Generate New Secret Keys - Done");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #13
0
        public virtual IActionResult BceidValidateOwner([FromQuery] string sharedKey, [FromQuery] string postalCode)
        {
            string businessGuid = UserAccountHelper.GetBusinessGuid(_httpContext, _env);

            if (string.IsNullOrEmpty(sharedKey))
            {
                // shared key not provided
                return(new BadRequestObjectResult(new HetsResponse("HETS-19", ErrorViewModel.GetDescription("HETS-19", _configuration))));
            }

            if (string.IsNullOrEmpty(postalCode))
            {
                // postal code not provided
                return(new BadRequestObjectResult(new HetsResponse("HETS-22", ErrorViewModel.GetDescription("HETS-22", _configuration))));
            }

            bool exists = _context.HetBusiness.Any(a => a.BceidBusinessGuid.ToLower().Trim() == businessGuid.ToLower().Trim());

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

            // get business
            HetBusiness business = _context.HetBusiness.AsNoTracking()
                                   .First(x => x.BceidBusinessGuid.ToLower().Trim() == businessGuid.ToLower().Trim());

            // find owner using shred key & postal code (exact match)
            HetOwner owner = _context.HetOwner
                             .Include(a => a.Business)
                             .FirstOrDefault(a => a.SharedKey.Equals(sharedKey) &&
                                             a.PostalCode.Replace(" ", "").ToLower().Equals(postalCode.Replace(" ", "").ToLower(), StringComparison.InvariantCultureIgnoreCase));

            // validate the key
            if (owner == null)
            {
                // shared key not found
                return(new BadRequestObjectResult(new HetsResponse("HETS-20", ErrorViewModel.GetDescription("HETS-20", _configuration))));
            }

            if (owner.BusinessId != null)
            {
                // shared key already used
                return(new BadRequestObjectResult(new HetsResponse("HETS-21", ErrorViewModel.GetDescription("HETS-21", _configuration))));
            }

            // update owner
            int ownerId = owner.OwnerId;

            owner.BusinessId = business.BusinessId;
            owner.SharedKey  = null;
            _context.SaveChanges();

            // get updated business record and return to the UI
            business = _context.HetBusiness.AsNoTracking()
                       .Include(x => x.HetOwner)
                       .ThenInclude(y => y.PrimaryContact)
                       .Include(x => x.HetOwner)
                       .ThenInclude(y => y.Business)
                       .Include(x => x.HetOwner)
                       .ThenInclude(y => y.LocalArea.ServiceArea.District)
                       .FirstOrDefault(a => a.BusinessId == business.BusinessId);

            // get updated owner record (linked owner) and return to the UI too
            if (business != null)
            {
                business.LinkedOwner = _context.HetOwner.AsNoTracking()
                                       .FirstOrDefault(x => x.OwnerId == ownerId);
            }

            return(new ObjectResult(new HetsResponse(business)));
        }
Beispiel #14
0
        /// <summary>
        /// Import Owner Records
        /// </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.    // 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 maxOwnerIndex = 0;

            if (dbContext.HetOwner.Any())
            {
                maxOwnerIndex = dbContext.HetOwner.Max(x => x.OwnerId);
            }

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

                int ii = startPoint;

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

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

                foreach (ImportModels.Owner 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.Popt_Id.ToString());

                    // new entry
                    if (importMap == null)
                    {
                        HetOwner owner = null;
                        CopyToInstance(dbContext, item, ref owner, systemId, ref maxOwnerIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, item.Popt_Id.ToString(), NewTable, owner.OwnerId);
                    }

                    // 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)
                        {
                            string temp = string.Format("Error saving data (OwnerIndex: {0}): {1}", maxOwnerIndex, e.Message);
                            performContext.WriteLine(temp);
                            throw new DataException(temp);
                        }
                    }
                }

                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 (OwnerIndex: {0}): {1}", maxOwnerIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
Beispiel #15
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 #16
0
        /// <summary>
        /// Generate secret keys
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        public static void GenerateSecretKeys(PerformContext performContext, DbAppContext dbContext)
        {
            try
            {
                performContext.WriteLine("*** Generating New Secret Keys ***");
                Debug.WriteLine("Generating New Secret Keys");

                int    ii = 0;
                string _oldTableProgress = "SecretKeys_Progress";
                string _newTable         = "SecretKeys";

                // check if the secret keys have 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("*** Generating New Secret Key is complete from the former process ***");
                    return;
                }

                // get records
                List <HetOwner> owners = dbContext.HetOwner.AsNoTracking()
                                         .Where(x => x.BusinessId == null)
                                         .ToList();

                int i = 0;

                foreach (HetOwner owner in owners)
                {
                    i++;
                    string key = SecretKeyHelper.RandomString(8, owner.OwnerId);

                    string temp = owner.OwnerCode;

                    if (string.IsNullOrEmpty(temp))
                    {
                        temp = SecretKeyHelper.RandomString(4, owner.OwnerId);
                    }

                    key = temp + "-" + DateTime.UtcNow.Year + "-" + key;

                    // get owner and update
                    HetOwner ownerRecord = dbContext.HetOwner.First(x => x.OwnerId == owner.OwnerId);
                    ownerRecord.SharedKey = key;

                    if (i % 500 == 0)
                    {
                        dbContext.SaveChangesForImport();
                    }

                    // save change to database
                    if (ii++ % 100 == 0)
                    {
                        try
                        {
                            Debug.WriteLine("Generating New Secret Keys - Index: " + ii);
                            ImportUtility.AddImportMapForProgress(dbContext, _oldTableProgress, ii.ToString(), BcBidImport.SigId, _newTable);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                // ************************************************************
                // save final set of updates
                // ************************************************************
                try
                {
                    performContext.WriteLine("*** Done generating New Secret Keys ***");
                    Debug.WriteLine("Generating New Secret Keys 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)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #17
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="owner"></param>
        /// <param name="systemId"></param>
        /// <param name="maxOwnerIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Owner oldObject,
                                           ref HetOwner owner, string systemId, ref int maxOwnerIndex)
        {
            try
            {
                if (owner != null)
                {
                    return;
                }

                owner = new HetOwner {
                    OwnerId = ++maxOwnerIndex
                };

                // ***********************************************
                // set owner code
                // ***********************************************
                string tempOwnerCode = ImportUtility.CleanString(oldObject.Owner_Cd).ToUpper();

                if (!string.IsNullOrEmpty(tempOwnerCode))
                {
                    owner.OwnerCode = tempOwnerCode;
                }
                else
                {
                    // must have an owner code: HETS-817
                    return;
                }

                // ***********************************************
                // set company name
                // ***********************************************
                string tempCompanyName = ImportUtility.CleanString(oldObject.Company_Name);

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

                    // fix some capital case names
                    tempCompanyName = tempCompanyName.Replace("Bc", "BC");
                    tempCompanyName = tempCompanyName.Replace("Rv", "RV");
                    tempCompanyName = tempCompanyName.Replace(", & ", " & ");

                    owner.OrganizationName = tempCompanyName;
                }

                // ***********************************************
                // DBA Name
                // ***********************************************
                string tempDbaName = ImportUtility.CleanString(oldObject.Operating_AS);

                if (!string.IsNullOrEmpty(tempDbaName))
                {
                    tempDbaName           = ImportUtility.GetCapitalCase(tempDbaName);
                    owner.DoingBusinessAs = tempDbaName;
                }

                // ***********************************************
                // maintenance contractor
                // ***********************************************
                if (oldObject.Maintenance_Contractor != null)
                {
                    owner.IsMaintenanceContractor = (oldObject.Maintenance_Contractor.Trim() == "Y");
                }

                // ***********************************************
                // residency
                // ***********************************************
                if (oldObject.Local_To_Area != null)
                {
                    owner.MeetsResidency = (oldObject.Local_To_Area.Trim() == "Y");
                }

                // ***********************************************
                // set local area
                // ***********************************************
                HetLocalArea localArea = dbContext.HetLocalArea.FirstOrDefault(x => x.LocalAreaId == oldObject.Area_Id);

                if (localArea != null)
                {
                    owner.LocalAreaId = localArea.LocalAreaId;
                }

                // ***********************************************
                // set other attributes
                // ***********************************************
                owner.WorkSafeBcexpiryDate = ImportUtility.CleanDate(oldObject.CGL_End_Dt);
                owner.CglendDate           = ImportUtility.CleanDate(oldObject.CGL_End_Dt);

                owner.WorkSafeBcpolicyNumber = ImportUtility.CleanString(oldObject.WCB_Num);

                if (owner.WorkSafeBcpolicyNumber == "0")
                {
                    owner.WorkSafeBcpolicyNumber = null;
                }

                string tempCglCompanyName = ImportUtility.CleanString(oldObject.CGL_Company);
                tempCglCompanyName = ImportUtility.GetCapitalCase(tempCglCompanyName);

                if (!string.IsNullOrEmpty(tempCglCompanyName))
                {
                    owner.CglCompanyName = tempCglCompanyName;
                }

                owner.CglPolicyNumber = ImportUtility.CleanString(oldObject.CGL_Policy);

                if (owner.CglPolicyNumber == "")
                {
                    owner.CglPolicyNumber = null;
                }

                // ***********************************************
                // manage archive and owner status
                // ***********************************************
                string tempArchive = oldObject.Archive_Cd;
                string tempStatus  = oldObject.Status_Cd.Trim();

                if (tempArchive == "Y")
                {
                    int?statusId = StatusHelper.GetStatusId("Archived", "ownerStatus", dbContext);

                    if (statusId == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (OwnerIndex: {0}", maxOwnerIndex));
                    }

                    // archived!
                    owner.ArchiveCode       = "Y";
                    owner.ArchiveDate       = DateTime.UtcNow;
                    owner.ArchiveReason     = "Imported from BC Bid";
                    owner.OwnerStatusTypeId = (int)statusId;

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

                    if (!string.IsNullOrEmpty(tempArchiveReason))
                    {
                        owner.ArchiveReason = ImportUtility.GetUppercaseFirst(tempArchiveReason);
                    }
                }
                else
                {
                    int?statusId = StatusHelper.GetStatusId("Approved", "ownerStatus", dbContext);

                    if (statusId == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (OwnerIndex: {0}", maxOwnerIndex));
                    }

                    int?statusIdUnapproved = StatusHelper.GetStatusId("Unapproved", "ownerStatus", dbContext);

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

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

                // ***********************************************
                // manage owner information
                // ***********************************************
                string tempOwnerFirstName = ImportUtility.CleanString(oldObject.Owner_First_Name);
                tempOwnerFirstName = ImportUtility.GetCapitalCase(tempOwnerFirstName);

                string tempOwnerLastName = ImportUtility.CleanString(oldObject.Owner_Last_Name);
                tempOwnerLastName = ImportUtility.GetCapitalCase(tempOwnerLastName);

                // some fields have duplicates in the name
                if (tempOwnerLastName == tempOwnerFirstName)
                {
                    tempOwnerFirstName = "";
                }

                if (!string.IsNullOrEmpty(tempOwnerLastName))
                {
                    owner.Surname = tempOwnerLastName;
                }

                if (!string.IsNullOrEmpty(tempOwnerFirstName))
                {
                    owner.GivenName = tempOwnerFirstName;
                }

                // if there is no company name - create one
                string tempName = "";

                if (string.IsNullOrEmpty(tempCompanyName) &&
                    !string.IsNullOrEmpty(owner.OwnerCode) &&
                    string.IsNullOrEmpty(tempOwnerLastName))
                {
                    owner.OrganizationName = owner.OwnerCode;
                    tempName = owner.OrganizationName;
                }
                else if (string.IsNullOrEmpty(tempCompanyName) && !string.IsNullOrEmpty(owner.OwnerCode))
                {
                    owner.OrganizationName = string.Format("{0} - {1} {2}", owner.OwnerCode, tempOwnerFirstName, tempOwnerLastName);
                    tempName = owner.OrganizationName;
                }
                else if (string.IsNullOrEmpty(tempCompanyName))
                {
                    owner.OrganizationName = string.Format("{0} {1}", tempOwnerFirstName, tempOwnerLastName);
                    tempName = owner.OrganizationName;
                }

                // check if the organization name is actually a "Ltd" or other company name
                // (in BC Bid the names are sometimes used to store the org)
                if (!string.IsNullOrEmpty(tempName) &&
                    tempName.IndexOf(" Ltd", StringComparison.Ordinal) > -1 ||
                    tempName.IndexOf(" Resort", StringComparison.Ordinal) > -1 ||
                    tempName.IndexOf(" Oilfield", StringComparison.Ordinal) > -1 ||
                    tempName.IndexOf(" Nation", StringComparison.Ordinal) > -1 ||
                    tempName.IndexOf(" Ventures", StringComparison.Ordinal) > -1 ||
                    tempName.IndexOf(" Indian Band", StringComparison.Ordinal) > -1)
                {
                    owner.Surname   = null;
                    owner.GivenName = null;

                    if (!string.IsNullOrEmpty(owner.OwnerCode))
                    {
                        owner.OrganizationName = string.Format("{0} {1}", tempOwnerFirstName, tempOwnerLastName);
                    }
                }

                // ***********************************************
                // format company names
                // ***********************************************
                if (owner.OrganizationName.EndsWith(" Ltd") ||
                    owner.OrganizationName.EndsWith(" Ulc") ||
                    owner.OrganizationName.EndsWith(" Inc") ||
                    owner.OrganizationName.EndsWith(" Co"))
                {
                    owner.OrganizationName = owner.OrganizationName + ".";
                }

                // ***********************************************
                // manage contacts
                // ***********************************************
                bool contactExists = false;

                if (owner.HetContact != null)
                {
                    foreach (HetContact contactItem in owner.HetContact)
                    {
                        if (!string.Equals(contactItem.GivenName, tempOwnerFirstName, StringComparison.InvariantCultureIgnoreCase) &&
                            !string.Equals(contactItem.Surname, tempOwnerLastName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            contactExists = true;
                        }
                    }
                }

                string tempPhone  = ImportUtility.FormatPhone(oldObject.Ph_Country_Code, oldObject.Ph_Area_Code, oldObject.Ph_Number, oldObject.Ph_Extension);
                string tempFax    = ImportUtility.FormatPhone(oldObject.Fax_Country_Code, oldObject.Fax_Area_Code, oldObject.Fax_Number, oldObject.Fax_Extension);
                string tempMobile = ImportUtility.FormatPhone(oldObject.Cell_Country_Code, oldObject.Cell_Area_Code, oldObject.Cell_Number, oldObject.Cell_Extension);

                // only add if they don't already exist
                if (!contactExists && !string.IsNullOrEmpty(tempOwnerLastName))
                {
                    HetContact ownerContact = new HetContact
                    {
                        Role                   = "Owner",
                        Province               = "BC",
                        Notes                  = "",
                        WorkPhoneNumber        = tempPhone,
                        MobilePhoneNumber      = tempMobile,
                        FaxPhoneNumber         = tempFax,
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    if (!string.IsNullOrEmpty(tempOwnerLastName))
                    {
                        ownerContact.Surname = tempOwnerLastName;
                    }

                    if (!string.IsNullOrEmpty(tempOwnerFirstName))
                    {
                        ownerContact.GivenName = tempOwnerFirstName;
                    }

                    if (owner.HetContact == null)
                    {
                        owner.HetContact = new List <HetContact>();
                    }

                    owner.HetContact.Add(ownerContact);
                }

                // is the BC Bid contact the same as the owner?
                string tempContactPerson = ImportUtility.CleanString(oldObject.Contact_Person);
                tempContactPerson = ImportUtility.GetCapitalCase(tempContactPerson);

                if (!string.IsNullOrEmpty(tempContactPerson))
                {
                    string tempContactPhone = ImportUtility.FormatPhone(oldObject.Contact_Country_Code, oldObject.Contact_Area_Code, oldObject.Contact_Number, oldObject.Contact_Extension);

                    // split the name
                    string tempContactFirstName;
                    string tempContactLastName;

                    if (tempContactPerson.IndexOf(" Or ", StringComparison.Ordinal) > -1)
                    {
                        tempContactFirstName = tempContactPerson;
                        tempContactLastName  = "";
                    }
                    else
                    {
                        tempContactFirstName = ImportUtility.GetNamePart(tempContactPerson, 1);
                        tempContactLastName  = ImportUtility.GetNamePart(tempContactPerson, 2);
                    }

                    // check if the name is unique
                    if ((!string.Equals(tempContactFirstName, tempOwnerFirstName, StringComparison.InvariantCultureIgnoreCase) &&
                         !string.Equals(tempContactLastName, tempOwnerLastName, StringComparison.InvariantCultureIgnoreCase)) ||
                        (!string.Equals(tempContactFirstName, tempOwnerFirstName, StringComparison.InvariantCultureIgnoreCase) &&
                         !string.Equals(tempContactFirstName, tempOwnerLastName, StringComparison.InvariantCultureIgnoreCase) &&
                         !string.IsNullOrEmpty(tempContactLastName)))
                    {
                        // check if the name(s) already exist
                        contactExists = false;

                        if (owner.HetContact != null)
                        {
                            foreach (HetContact contactItem in owner.HetContact)
                            {
                                if (string.Equals(contactItem.GivenName, tempContactFirstName, StringComparison.InvariantCultureIgnoreCase) &&
                                    string.Equals(contactItem.Surname, tempContactLastName, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    contactExists = true;
                                }
                            }
                        }

                        if (!contactExists)
                        {
                            string tempPhoneNumber = "";

                            if (tempPhone != tempContactPhone && !string.IsNullOrEmpty(tempContactPhone))
                            {
                                tempPhoneNumber = tempContactPhone;
                            }

                            HetContact primaryContact = new HetContact
                            {
                                Role                   = "Primary Contact",
                                Province               = "BC",
                                WorkPhoneNumber        = tempPhone,
                                MobilePhoneNumber      = tempMobile,
                                FaxPhoneNumber         = tempFax,
                                Notes                  = tempPhoneNumber,
                                AppCreateUserid        = systemId,
                                AppCreateTimestamp     = DateTime.UtcNow,
                                AppLastUpdateUserid    = systemId,
                                AppLastUpdateTimestamp = DateTime.UtcNow
                            };

                            if (!string.IsNullOrEmpty(tempContactLastName))
                            {
                                primaryContact.Surname = tempContactLastName;
                            }

                            if (!string.IsNullOrEmpty(tempContactFirstName))
                            {
                                primaryContact.GivenName = tempContactFirstName;
                            }

                            string tempComment = ImportUtility.CleanString(oldObject.Comment);

                            if (!string.IsNullOrEmpty(tempComment))
                            {
                                tempComment          = ImportUtility.GetCapitalCase(tempComment);
                                primaryContact.Notes = tempComment;
                            }

                            owner.PrimaryContact = primaryContact; // since this was the default in the file - make it primary
                        }
                    }
                }

                // ensure the contact is valid
                if (owner.HetContact != null)
                {
                    for (int i = owner.HetContact.Count - 1; i >= 0; i--)
                    {
                        if (string.IsNullOrEmpty(owner.HetContact.ElementAt(i).GivenName) &&
                            string.IsNullOrEmpty(owner.HetContact.ElementAt(i).Surname))
                        {
                            owner.HetContact.Remove(owner.HetContact.ElementAt(i));
                        }
                    }

                    // update primary
                    if (owner.HetContact.Count > 0 &&
                        owner.PrimaryContact == null)
                    {
                        owner.PrimaryContact = owner.HetContact.ElementAt(0);
                        owner.HetContact.Remove(owner.HetContact.ElementAt(0));
                    }
                }

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

                dbContext.HetOwner.Add(owner);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Owner Code: " + owner.OwnerCode);
                Debug.WriteLine("***Error*** - Master Owner Index: " + maxOwnerIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }