Exemple #1
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, Equip oldObject, ref Equipment equipment, string systemId, ref int maxEquipmentIndex)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                equipment = new Equipment {
                    Id = ++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;
                }

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

                if (tempArchive == "Y")
                {
                    // archived!
                    equipment.ArchiveCode   = "Y";
                    equipment.ArchiveDate   = DateTime.UtcNow;
                    equipment.ArchiveReason = "Imported from BC Bid";
                    equipment.Status        = "Archived";

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

                    if (!string.IsNullOrEmpty(tempArchiveReason))
                    {
                        equipment.ArchiveReason = ImportUtility.GetUppercaseFirst(tempArchiveReason);
                    }
                }
                else
                {
                    equipment.ArchiveCode   = "N";
                    equipment.ArchiveDate   = null;
                    equipment.ArchiveReason = null;
                    equipment.Status        = tempStatus == "A" ? "Approved" : "Unapproved";
                    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.CleanDateTime(oldObject.Approved_Dt);

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

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

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

                if (!string.IsNullOrEmpty(tempEquipmentCode))
                {
                    equipment.EquipmentCode = tempEquipmentCode;
                }
                else
                {
                    if (equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                    {
                        throw new DataException(string.Format("Equipment Code cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                    }
                }

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

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

                // ***********************************************
                // make, model, year, etc.
                // ***********************************************
                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);

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

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

                    equipment.Notes.Add(note);
                }

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

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

                if (equipment.LocalAreaId == null && equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                {
                    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();

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

                    if (equipMap != null)
                    {
                        DistrictEquipmentType distEquipType = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == equipMap.NewKey);

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

                        // is this a dump truck?
                        if (!string.IsNullOrEmpty(oldObject.Reg_Dump_Trk) && oldObject.Reg_Dump_Trk == "Y")
                        {
                            // update the equipment type record -> IsDumpTruck = True
                            EquipmentType equipType = dbContext.EquipmentTypes.FirstOrDefault(x => x.Id == distEquipType.EquipmentTypeId);

                            if (equipType != null)
                            {
                                equipType.IsDumpTruck = true;
                                dbContext.EquipmentTypes.Update(equipType);
                            }
                        }
                    }
                }

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

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

                if (ownerMap != null)
                {
                    Models.Owner owner = dbContext.Owners.FirstOrDefault(x => x.Id == ownerMap.NewKey);

                    if (owner != null)
                    {
                        int tempOwnerId = owner.Id;
                        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.Owners.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;

                // ***********************************************
                // 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.Equipments.Add(equipment);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Code: " + equipment.EquipmentCode);
                Debug.WriteLine("***Error*** - Master Equipment Index: " + maxEquipmentIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Exemple #2
0
        /// <summary>
        /// Copy Block item of LocalAreaRotationList item
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="rotationList"></param>
        /// <param name="systemId"></param>
        /// <param name="maxBlockIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, Block oldObject, ref LocalAreaRotationList 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
                }

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

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

                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.Created_Dt;

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

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

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

                // ***********************************************
                // get the area record
                // ***********************************************
                string tempOldAreaId = oldObject.Area_Id.ToString();

                ImportMap mapArea = dbContext.ImportMaps.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));
                }

                LocalArea area = dbContext.LocalAreas.AsNoTracking()
                                 .FirstOrDefault(x => x.Id == 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();

                ImportMap mapEquipType = dbContext.ImportMaps.AsNoTracking()
                                         .FirstOrDefault(x => x.OldKey == tempOldEquipTypeId &&
                                                         x.OldTable == ImportDistrictEquipmentType.OldTable &&
                                                         x.NewTable == ImportDistrictEquipmentType.NewTable);

                if (mapEquipType == null)
                {
                    throw new DataException(string.Format("Equipment Type Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                DistrictEquipmentType equipmentType = dbContext.DistrictEquipmentTypes.AsNoTracking()
                                                      .FirstOrDefault(x => x.Id == 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.LocalAreaRotationLists
                               .FirstOrDefault(x => x.LocalAreaId == area.Id &&
                                               x.DistrictEquipmentTypeId == equipmentType.Id);

                if (rotationList == null)
                {
                    isNew = true;

                    // create new list
                    rotationList = new LocalAreaRotationList
                    {
                        Id                      = ++maxBlockIndex,
                        LocalAreaId             = area.Id,
                        DistrictEquipmentTypeId = equipmentType.Id,
                        AppCreateUserid         = systemId,
                        AppCreateTimestamp      = DateTime.UtcNow
                    };
                }
                else
                {
                    // record already exists - just testing updates
                    Debug.WriteLine("Record Id: " + rotationList.Id);
                }

                // ***********************************************
                // get the equipment record
                // ***********************************************
                string tempOldEquipId = oldObject.Last_Hired_Equip_Id.ToString();

                ImportMap mapEquip = dbContext.ImportMaps.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));
                }

                Equipment equipment = dbContext.Equipments.AsNoTracking()
                                      .FirstOrDefault(x => x.Id == 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
                switch (blockNum)
                {
                case 1:
                    rotationList.AskNextBlock1Id        = equipment.Id;
                    rotationList.AskNextBlock1Seniority = equipment.Seniority;
                    break;

                case 2:
                    rotationList.AskNextBlock2Id        = equipment.Id;
                    rotationList.AskNextBlock2Seniority = equipment.Seniority;
                    break;

                case 3:
                    rotationList.AskNextBlockOpenId = equipment.Id;
                    break;
                }

                // ***********************************************
                // update or create equipment
                // ***********************************************
                equipment.AppLastUpdateUserid    = systemId;
                equipment.AppLastUpdateTimestamp = DateTime.UtcNow;

                if (isNew)
                {
                    dbContext.LocalAreaRotationLists.Add(rotationList);
                }
                else
                {
                    dbContext.LocalAreaRotationLists.Update(rotationList);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Master Block Index: " + maxBlockIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Exemple #3
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 Owner owner, string systemId, ref int maxOwnerIndex)
        {
            try
            {
                if (owner != null)
                {
                    return;
                }

                owner = new Owner {
                    Id = ++maxOwnerIndex
                };

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

                if (!string.IsNullOrEmpty(tempOwnerCode))
                {
                    owner.OwnerCode = tempOwnerCode;
                }

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

                // ***********************************************
                // set local area
                // ***********************************************
                LocalArea localArea = dbContext.LocalAreas.FirstOrDefault(x => x.Id == oldObject.Area_Id);

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

                // ***********************************************
                // set other attributes
                // ***********************************************
                owner.WorkSafeBCExpiryDate = ImportUtility.CleanDateTime(oldObject.CGL_End_Dt);
                owner.CGLEndDate           = ImportUtility.CleanDateTime(oldObject.CGL_End_Dt);

                owner.WorkSafeBCPolicyNumber = ImportUtility.CleanString(oldObject.WCB_Num);
                if (owner.WorkSafeBCPolicyNumber == "0")
                {
                    owner.WorkSafeBCPolicyNumber = null;
                }

                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")
                {
                    // archived!
                    owner.ArchiveCode   = "Y";
                    owner.ArchiveDate   = DateTime.UtcNow;
                    owner.ArchiveReason = "Imported from BC Bid";
                    owner.Status        = "Archived";

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

                    if (!string.IsNullOrEmpty(tempArchiveReason))
                    {
                        owner.ArchiveReason = ImportUtility.GetUppercaseFirst(tempArchiveReason);
                    }
                }
                else
                {
                    owner.ArchiveCode   = "N";
                    owner.ArchiveDate   = null;
                    owner.ArchiveReason = null;
                    owner.Status        = tempStatus == "A" ? "Approved" : "Unapproved";
                    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;
                }

                // no company name (yet) will create one for now
                if (!string.IsNullOrEmpty(owner.OwnerCode) &&
                    string.IsNullOrEmpty(tempOwnerLastName))
                {
                    owner.OrganizationName = owner.OwnerCode;
                }
                else if (!string.IsNullOrEmpty(owner.OwnerCode))
                {
                    owner.OrganizationName = string.Format("{0} - {1} {2}", owner.OwnerCode, tempOwnerFirstName, tempOwnerLastName);
                }
                else
                {
                    owner.OrganizationName = string.Format("{0} {1}", tempOwnerFirstName, tempOwnerLastName);
                }

                // check if the organization name is actually a "Ltd" or other company name
                // (in BC Bid the names are somtimes used to store the org)
                if (owner.OrganizationName.IndexOf(" Ltd", StringComparison.Ordinal) > -1 ||
                    owner.OrganizationName.IndexOf(" Resort", StringComparison.Ordinal) > -1 ||
                    owner.OrganizationName.IndexOf(" Oilfield", StringComparison.Ordinal) > -1 ||
                    owner.OrganizationName.IndexOf(" Nation", StringComparison.Ordinal) > -1 ||
                    owner.OrganizationName.IndexOf(" Ventures", StringComparison.Ordinal) > -1 ||
                    owner.OrganizationName.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);
                    }
                }

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

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

                // only add if they don't already exist
                if (!contactExists && !string.IsNullOrEmpty(tempOwnerLastName))
                {
                    Contact ownerContact = new Contact
                    {
                        Role                   = "Owner",
                        Province               = "BC",
                        Notes                  = "",
                        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.Contacts == null)
                    {
                        owner.Contacts = new List <Contact>();
                    }

                    owner.Contacts.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))
                {
                    // 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.Contacts != null)
                        {
                            foreach (Contact contactItem in owner.Contacts)
                            {
                                if (String.Equals(contactItem.GivenName, tempContactFirstName, StringComparison.InvariantCultureIgnoreCase) &&
                                    String.Equals(contactItem.Surname, tempContactLastName, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    contactExists = true;
                                }
                            }
                        }

                        if (!contactExists)
                        {
                            Contact primaryContact = new Contact
                            {
                                Role                   = "Primary Contact",
                                Province               = "BC",
                                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.Contacts != null)
                {
                    for (int i = owner.Contacts.Count - 1; i >= 0; i--)
                    {
                        if (string.IsNullOrEmpty(owner.Contacts[i].GivenName) &&
                            string.IsNullOrEmpty(owner.Contacts[i].Surname))
                        {
                            owner.Contacts.RemoveAt(i);
                        }
                    }

                    // update primary
                    if (owner.Contacts.Count > 0 &&
                        owner.PrimaryContact == null)
                    {
                        owner.PrimaryContact = owner.Contacts[0];
                        owner.Contacts.Remove(owner.Contacts[0]);
                    }
                }

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

                dbContext.Owners.Add(owner);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Owner Code: " + owner.OwnerCode);
                Debug.WriteLine("***Error*** - Master Owner Index: " + maxOwnerIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Exemple #4
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, EquipUsage oldObject, ref TimeRecord 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;
                DateTime fiscalEnd;

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

                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.CleanDateTime(tempRecordDate);

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


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

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

                if (mapEquip == null)
                {
                    throw new DataException(string.Format("Cannot locate Equipment record (Timesheet Equip Id: {0}", tempId));
                }

                // ***********************************************
                // find the equipment record
                // ***********************************************
                Equipment equipment = dbContext.Equipments.AsNoTracking().FirstOrDefault(x => x.Id == mapEquip.NewKey);

                if (equipment == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate Equipment record (Timesheet Equip Id: {0}", tempId));
                }

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

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

                // ***********************************************
                // find the project record
                // (or create a project (inactive))
                // ***********************************************
                Models.Project project;

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

                    if (project == null)
                    {
                        throw new ArgumentException(string.Format("Cannot locate Project record (Timesheet Equip Id: {0}", tempId));
                    }
                }
                else
                {
                    // create new project
                    project = new Models.Project
                    {
                        Information            = "Created to support Time Record import from BCBid",
                        Status                 = "Complete",
                        Name                   = "Legacy BCBid Project",
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    dbContext.Projects.Add(project);

                    // save now so we can access it for other time records
                    dbContext.SaveChanges();

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

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

                RentalAgreement agreement = dbContext.RentalAgreements.AsNoTracking()
                                            .FirstOrDefault(x => x.EquipmentId == equipment.Id &&
                                                            x.ProjectId == project.Id);

                if (agreement == null)
                {
                    // create a new agreement record
                    agreement = new RentalAgreement
                    {
                        EquipmentId            = equipment.Id,
                        ProjectId              = project.Id,
                        Note                   = "Created to support Time Record import from BCBid",
                        Number                 = "Legacy BCBid Agreement",
                        DatedOn                = enteredDate,
                        AppCreateUserid        = systemId,
                        AppCreateTimestamp     = DateTime.UtcNow,
                        AppLastUpdateUserid    = systemId,
                        AppLastUpdateTimestamp = DateTime.UtcNow
                    };

                    if (project.RentalAgreements == null)
                    {
                        project.RentalAgreements = new List <RentalAgreement>();
                    }

                    project.RentalAgreements.Add(agreement);

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

                // ***********************************************
                // create time record
                // ***********************************************
                timeRecord = new TimeRecord {
                    Id = ++maxTimesheetIndex
                };

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

                if (workedDate != null)
                {
                    timeRecord.WorkedDate = (DateTime)workedDate;
                }
                else
                {
                    throw new DataException(string.Format("Worked Date cannot be null (TimesheetIndex: {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 (TimesheetIndex: {0}", maxTimesheetIndex));
                }

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

                // ***********************************************
                // create time record
                // ***********************************************
                timeRecord.AppCreateUserid        = systemId;
                timeRecord.AppCreateTimestamp     = DateTime.UtcNow;
                timeRecord.AppLastUpdateUserid    = systemId;
                timeRecord.AppLastUpdateTimestamp = DateTime.UtcNow;

                if (agreement.TimeRecords == null)
                {
                    agreement.TimeRecords = new List <TimeRecord>();
                }

                agreement.TimeRecords.Add(timeRecord);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Worked Date: " + oldObject.Worked_Dt);
                Debug.WriteLine("***Error*** - Master TimeRecord Index: " + maxTimesheetIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }