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

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

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

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

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

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

            // recalculate the seniority list
            SeniorityListHelper.CalculateSeniorityList(localArea.LocalAreaId,
                                                       districtEquipmentType.DistrictEquipmentTypeId,
                                                       context,
                                                       seniorityScoringRules);
        }
Ejemplo n.º 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)
            {
                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);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="localArea"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Area oldObject,
                                           ref HetLocalArea localArea, string systemId)
        {
            try
            {
                if (oldObject.Area_Id <= 0)
                {
                    return;
                }

                string tempLocalArea = ImportUtility.CleanString(oldObject.Area_Desc);
                tempLocalArea = ImportUtility.GetCapitalCase(tempLocalArea);

                localArea = new HetLocalArea
                {
                    LocalAreaId     = oldObject.Area_Id,
                    LocalAreaNumber = oldObject.Area_Id,
                    Name            = tempLocalArea
                };

                // map to the correct service area
                HetServiceArea serviceArea = dbContext.HetServiceArea.AsNoTracking()
                                             .FirstOrDefault(x => x.MinistryServiceAreaId == oldObject.Service_Area_Id);

                if (serviceArea == null)
                {
                    // not mapped correctly
                    return;
                }

                localArea.ServiceAreaId = serviceArea.ServiceAreaId;

                localArea.AppCreateUserid        = systemId;
                localArea.AppCreateTimestamp     = DateTime.UtcNow;
                localArea.AppLastUpdateUserid    = systemId;
                localArea.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.HetLocalArea.Add(localArea);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 4
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;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Import Local Areas
        /// </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;
            }

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

                int ii = startPoint;

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

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

                foreach (ImportModels.Area 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.Area_Id.ToString());

                    // new entry
                    if (importMap == null && item.Area_Id > 0)
                    {
                        HetLocalArea localArea = null;
                        CopyToInstance(dbContext, item, ref localArea, systemId);
                        ImportUtility.AddImportMap(dbContext, OldTable, item.Area_Id.ToString(), NewTable, localArea.LocalAreaId);
                    }
                }

                performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, NewTable);
                dbContext.SaveChangesForImport();
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
Ejemplo n.º 6
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;
            }
        }
Ejemplo n.º 7
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;
            }
        }