/// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="rotationDoc"></param>
        /// <param name="systemId"></param>
        /// <param name="maxIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.RotationDoc oldObject,
                                           ref BcbidRotationDoc rotationDoc, string systemId, ref int maxIndex)
        {
            try
            {
                if (rotationDoc != null)
                {
                    return;
                }

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

                // ***********************************************
                // we only need records from the current fiscal
                // so ignore all others
                // ***********************************************
                DateTime fiscalStart;

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

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

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

                rotationDoc.NoteType = noteType.Trim();

                // reason
                string reason = oldObject.Reason;

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

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

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

                rotationDoc.AskedDate = (DateTime)createdDate;


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

                // setup the reason
                string tempResponse = "";

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

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

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

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

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

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

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

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

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

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

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

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

                rotationDoc.OfferRefusalReason = tempResponse;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // ***********************************************
                // we only need records from the current fiscal
                // so ignore all others
                // ***********************************************
                DateTime fiscalStart;

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

                string tempRecordDate = oldObject.Worked_Dt;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                timeRecord.TimePeriodTypeId = (int)timePeriodTypeId;

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

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

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

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

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

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

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

                dbContext.HetTimeRecord.Add(timeRecord);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Worked Date: " + oldObject.Worked_Dt);
                Debug.WriteLine("***Error*** - Master Time Record Index: " + maxTimeSheetIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #4
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;
            }
        }