public async Task <GenericServiceResponse> GetLead(Guid leadGuid, LogCommand logCommand)
        {
            const string method = "GetLead";

            try
            {
                logCommand.LogMessage = string.Format($"{Service}.{method} Starting input parameter leadGuid = {0}", leadGuid);
                _logHandler.HandleLog(logCommand);

                var lead = await _leadRepository.GetLead(leadGuid, logCommand);

                var response = ServiceHelper.SetGenericServiceResponseForEntity(lead);
                response.Success = true;

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
Exemple #2
0
        public Task <GenericServiceResponse> CdcEventContactUpdate(JObject cdcPayload, LogCommand logCommand)
        {
            const string method = "CDCEventContactUpdate";

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter CDCPayload = {cdcPayload}";
                _logHandler.HandleLog(logCommand);


                var response = new GenericServiceResponse
                {
                    Entity             = $"Ignoring Contact ",
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Success
                };


                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(Task.Run(() => response));
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(Task.Run(() => ServiceHelper.SetErrorGenericServiceResponse(ex)));
            }
        }
Exemple #3
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            string exceptionMessage = string.Empty;

            if (actionExecutedContext.Exception.InnerException == null)
            {
                exceptionMessage = actionExecutedContext.Exception.Message;
            }
            else
            {
                exceptionMessage = actionExecutedContext.Exception.InnerException.Message;
            }

            int memberId = GetLoggedInMemberId(actionExecutedContext);

            actionExecutedContext.Exception.Data.Add("MemberID", memberId);

            //log this exception message
            AppLogger.LogException(actionExecutedContext.Exception);

            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content      = new StringContent("An unhandled exception was thrown by service."),
                ReasonPhrase = exceptionMessage
            };

            actionExecutedContext.Response = response;
        }
Exemple #4
0
 public override async Task Invoke(IOwinContext context)
 {
     try
     {
         await Next.Invoke(context);
     }
     catch (Exception ex)
     {
         AppLogger.ApplicationName = Assembly.GetExecutingAssembly().FullName;
         AppLogger.LogException(LoggingInstance, "Unhandled Global Exception caught by OWin GlobalExceptionMiddleware", ex);
     }
 }
Exemple #5
0
 public override void Handle(ExceptionHandlerContext context)
 {
     //StringBuilder sb = new StringBuilder();
     //DataContractSerializer xmlserializer = new DataContractSerializer(context.Exception.GetType());
     //using (XmlWriter writer = XmlWriter.Create(sb))
     //{
     //    xmlserializer.WriteObject(writer, context.Exception);
     //    writer.Close();
     //}
     AppLogger.LogException(_loggingInstance, "WebApi: Logging from WebApi UnhandledExceptionLogger", context.Exception);
     base.Handle(context);
 }
        /// <summary>
        /// Sends a notification email out about actions taken by the service.
        /// </summary>
        /// <param name="automatedEmail"></param>
        /// <param name="loggingInstance"></param>
        /// <returns></returns>
        public bool SendNotification(AutomatedEmail automatedEmail, ILog loggingInstance)
        {
            try
            {
                var senderAddress = ConfigurationManager.AppSettings["EmailSenderAddress"];

                var receiverAddressList = automatedEmail.RecipientList();

                var smtpHost = ConfigurationManager.AppSettings["EmailSmtpHost"];
                var password = Encoding.UTF8.GetString(Convert.FromBase64String(ConfigurationManager.AppSettings["EmailPassword"]));

                var mail = new MailMessage
                {
                    From = new MailAddress(senderAddress)
                };
                foreach (var receiverAddress in receiverAddressList)
                {
                    mail.To.Add(receiverAddress);
                }
                foreach (var ccAddress in automatedEmail.CcList())
                {
                    mail.CC.Add(ccAddress);
                }
                foreach (var bccAddress in automatedEmail.BccList())
                {
                    mail.Bcc.Add(bccAddress);
                }
                var client = new SmtpClient(smtpHost, 587);
                mail.IsBodyHtml = true;
                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential(senderAddress, password);
                client.EnableSsl             = true;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                mail.Subject  = automatedEmail.EmailSubject;
                mail.Body     = automatedEmail.EmailBody;
                mail.Priority = automatedEmail.Priority;

                client.Send(mail);

                return(true);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(loggingInstance, ex.Message, ex);
                return(false);
            }
        }
Exemple #7
0
        //Change Minor
        //TODO: HW This is temporary code Needs to be removed ASAP Hack to update Lead so that it will be excluded from GetPrioritizedLeads query if touched by user.
        public Task <GenericServiceResponse> TaskEventInsertUpdate(PayloadParent payloadResponse, LogCommand logCommand)
        {
            const string method = "TaskEventInsertUpdate";

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter cdcPayload = {JsonConvert.SerializeObject(payloadResponse)}";
                _logHandler.HandleLog(logCommand);


                var response = AuditInsert.InsertAuditRecordAsync(logCommand, payloadResponse, "Shared.Entities.DTO.Customer.Lead", payloadResponse.CreatedById, _cdcRepository);
                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(Task.Run(() => ServiceHelper.SetErrorGenericServiceResponse(ex)));
            }
        }
        public async Task <GenericServiceResponse> ConvertLeadToAccount(PayloadParent responseObject, LogCommand logCommand)
        {
            const string method = "ConvertLeadToAccount";

            try
            {
                logCommand.LogMessage = string.Format($"{Service}.{method} Starting - ResponseObject: {responseObject}");
                _logHandler.HandleLog(logCommand);
                var rowsAffected = await _leadRepository.SetLeadStatusToConverted(responseObject.CmcCustomerGuidC, logCommand);

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                if (rowsAffected >= 1)
                {
                    return(new GenericServiceResponse
                    {
                        Entity = $"Lead Status Set To Converted, rows added/updated = {rowsAffected}",
                        Success = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Success
                    });
                }
                else
                {
                    return(new GenericServiceResponse
                    {
                        Entity = $"Lead Status Not Converted, rows added/updated = {rowsAffected}",
                        Success = false,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Error
                    });
                }
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
        public async Task <GenericServiceResponse> GetLead(SearchLeadSimple leadSearcher, LogCommand logCommand)
        {
            const string method = "GetLead";

            try
            {
                logCommand.LogMessage = string.Format($"{Service}.{method} Starting input parameter LeadSearcher = {JsonConvert.SerializeObject(0)}", leadSearcher);
                _logHandler.HandleLog(logCommand);

                var sfLeadList = await _leadRepository.GetSfLeads(leadSearcher, logCommand);

                var response = ServiceHelper.SetGenericServiceResponseForEntityList(sfLeadList);
                response.Success = true;

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);
                return(response);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
Exemple #10
0
        public async Task <GenericServiceResponse> SimpleServiceAppointmentHandler(PayloadParent responseObject, LogCommand logCommand)
        {
            const string method           = "ServiceAppointmentUpdate";
            var          updateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter ResponseObject = {responseObject}";
                _logHandler.HandleLog(logCommand);

                var serviceAppointmentPayload = new ServiceAppointmentPayload(responseObject);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter serviceAppointmentPayload = {serviceAppointmentPayload}";
                _logHandler.HandleLog(logCommand);

                Guid programGuid;

                //ProgramGuid
                updateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    //SubProgramGuid	ProgramGuid
                    // programGuid = Guid.Parse("8CC20C6D-13C2-424B-9EB3-194F653CC778");
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                ////SubprogramGuid
                //updateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                //if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC))
                //{
                //    var subprogram = await _programRepository.GetSubProgramSFID(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);
                //    subprogramGuid = subprogram.SubProgramGuid;
                //}
                //else
                //{
                //    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                //}
                updateEventState = "Attempting to Check Dates" + Environment.NewLine;
                if (serviceAppointmentPayload._PayloadBody.ServiceAppointment.SchedStartTime == null)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SchedStartTime ");
                }
                var scheduleStartTime = (DateTime)serviceAppointmentPayload._PayloadBody.ServiceAppointment.SchedStartTime;

                if (!DateTime.TryParse(serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedDate,
                                       out var lastModifiedDate))
                {
                    lastModifiedDate = DateTime.Now;
                }

                updateEventState = "Attempting to Map dataObject" + Environment.NewLine;
                var schedulingDataObject = new SimpleScheduling
                {
                    SfRecordID           = serviceAppointmentPayload._PayloadHeader.RecordIdC,
                    ProgramGuid          = programGuid,
                    SalesforceUser       = serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById,
                    Technician           = serviceAppointmentPayload._PayloadBody.ServiceAppointment.TechnicianGuidC,
                    WorkOrderType        = serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId,
                    ScheduleBit          = true,
                    ScheduleDateTime     = scheduleStartTime,
                    LastModifiedDateTime = lastModifiedDate
                };

                if (string.IsNullOrEmpty(schedulingDataObject.SfRecordID) ||
                    string.IsNullOrEmpty(schedulingDataObject.WorkOrderType) ||
                    string.IsNullOrEmpty(schedulingDataObject.SalesforceUser))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing required fields");
                }

                updateEventState = "Attempting to Execute First" + Environment.NewLine;
                var recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordFirst(schedulingDataObject, logCommand);

                if (recordsChanged > 0)
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Record Created in Simple Scheduling, rows affected = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Success
                    };

                    logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                    _logHandler.HandleLog(logCommand);

                    return(ServiceResponse);
                }

                updateEventState = "Attempting to get List" + Environment.NewLine;
                var simpleSchedulingList =
                    (await _schedulingRepository.GetSimpleScheduling(schedulingDataObject.SfRecordID, logCommand)).ToList();
                updateEventState = "Attempting to start reschedule logic" + Environment.NewLine;
                var simpleSchedulingList0 = simpleSchedulingList.Where(a => a.ScheduleBit == false).ToList();
                if (simpleSchedulingList0.Any())
                {
                    updateEventState = "Attempting to Rescheduled [1] " + Environment.NewLine;
                    var firstOrDefault = simpleSchedulingList0.OrderByDescending(a => a.SSID).FirstOrDefault();
                    if (
                        firstOrDefault != null && (schedulingDataObject.SalesforceUser != firstOrDefault.SalesforceUser &&
                                                   schedulingDataObject.LastModifiedDateTime > firstOrDefault.LastModifiedDateTime.AddMinutes(+5)
                                                   &&
                                                   (schedulingDataObject.WorkOrderType != firstOrDefault.WorkOrderType ||
                                                    schedulingDataObject.ScheduleDateTime != firstOrDefault.ScheduleDateTime ||
                                                    schedulingDataObject.Technician != firstOrDefault.Technician))
                        )
                    {
                        recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordReschedule(schedulingDataObject,
                                                                                                            logCommand);
                    }
                }
                else
                {
                    updateEventState = "Attempting to Rescheduled [2] " + Environment.NewLine;
                    var firstOrDefault = simpleSchedulingList.OrderByDescending(a => a.SSID)
                                         .FirstOrDefault(a => a.ScheduleBit);
                    if (firstOrDefault == null)
                    {
                        throw new Exception($"Error: {Service}.{method} -- Missing Created Date Record on Reschedule ");
                    }
                    if (schedulingDataObject.SalesforceUser != firstOrDefault.SalesforceUser &&
                        schedulingDataObject.LastModifiedDateTime > firstOrDefault.LastModifiedDateTime.AddMinutes(+30))
                    {
                        recordsChanged = await _schedulingRepository.CreateSimpleSchedulingRecordReschedule(schedulingDataObject,
                                                                                                            logCommand);
                    }
                }
                updateEventState = "Executions Complete" + Environment.NewLine;

                ServiceResponse = await InsertAuditRecordAsync(logCommand, responseObject,
                                                               schedulingDataObject.GetType().FullName,
                                                               serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                if (recordsChanged >= 1)
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Successful: Update Scheduling Related Table, rows added/updated = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Success
                    };
                }
                else
                {
                    ServiceResponse = new GenericServiceResponse
                    {
                        Entity             = $"Failure: Update Scheduling Related Table, rows added/updated = {recordsChanged}",
                        Success            = true,
                        RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                    };
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", updateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
Exemple #11
0
        public async Task <GenericServiceResponse> ServiceAppointmentUpdate(PayloadParent ResponseObject, LogCommand logCommand)
        {
            const string method           = "ServiceAppointmentUpdate";
            var          updateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter ResponseObject = {ResponseObject}";
                _logHandler.HandleLog(logCommand);

                var serviceAppointmentPayload = new ServiceAppointmentPayload(ResponseObject);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter serviceAppointmentPayload = {serviceAppointmentPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                Guid programGuid;
                Guid subprogramGuid;
                Guid WorkOrderScoreWeightingGuid;
                Guid StatusTypeGuid;
                Guid UsernameMappingGuid;

                //ProgramGuid
                updateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(serviceAppointmentPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    //SubProgramGuid	ProgramGuid
                    // programGuid = Guid.Parse("8CC20C6D-13C2-424B-9EB3-194F653CC778");
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                updateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(serviceAppointmentPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                // Mapping SFUserid To AD Username
                updateEventState = "Attempting To Get Map Status GUid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.ServiceAppointment.Status))
                {
                    var lkpSchedulingType = await _schedulingRepository.GetLkpSchedulingTypeEnum(logCommand);

                    var statusTypeMapping = lkpSchedulingType.FirstOrDefault(a => string.Equals(a.SchedulingTypeName, serviceAppointmentPayload._PayloadBody.ServiceAppointment.Status, StringComparison.CurrentCultureIgnoreCase));
                    if (statusTypeMapping != null)
                    {
                        StatusTypeGuid = statusTypeMapping.LkpSchedulingTypeGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Status GUid ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Status GUid ");
                }

                // LKPWorkOrderScoreMapping Workorder WorkTypeId
                updateEventState = "Attempting To Get Map Work Order Type Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId))
                {
                    var lkpAuditType = await _schedulingRepository.GetWorkOrderScoreWeightingEnum(logCommand);

                    var workOrderScoreMapping = lkpAuditType.FirstOrDefault(a => a.SalesforceRecordID == serviceAppointmentPayload._PayloadBody.WorkOrder.WorkTypeId);
                    if (workOrderScoreMapping != null)
                    {
                        WorkOrderScoreWeightingGuid = workOrderScoreMapping.WorkOrderScoreWeightingGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Map Work order Type ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Map Work order Type ");
                }

                // LKPWorkOrderScoreMapping Workorder WorkTypeId
                updateEventState = "Attempting To Get Username Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById))
                {
                    var usernameMappingList = await _schedulingRepository.GetUsernameMappingSFtoADEnum(logCommand);

                    var usernameMapping = usernameMappingList.FirstOrDefault(a => a.SalesForceUserRecordID == serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);
                    if (usernameMapping != null)
                    {
                        UsernameMappingGuid = usernameMapping.UsernameMappingSFtoADGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Cannot Map Username ");
                    }
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Cannot Map Username");
                }
                updateEventState = "Attempting Execute" + Environment.NewLine;


                var schedulingDataObject = new Scheduling()
                {
                    SubprogramGuid = subprogramGuid,
                    ProgramGuid    = programGuid,
                    WorkOrderScoreWeightingGuid = WorkOrderScoreWeightingGuid,
                    UsernameMappingSFtoADGuid   = UsernameMappingGuid,
                    CreatedDateTime             = DateTime.Now,
                    LkpSchedulingTypeGuid       = StatusTypeGuid,
                    SalesforceRecordID          = serviceAppointmentPayload._PayloadHeader.RecordIdC
                };

                recordsAffected = await _schedulingRepository.CreateNewSchedulingRecord(schedulingDataObject, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, ResponseObject,
                                                               schedulingDataObject.GetType().FullName,
                                                               serviceAppointmentPayload._PayloadBody.ServiceAppointment.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                updateEventState = "Executions Complete" + Environment.NewLine;


                ServiceResponse = new GenericServiceResponse
                {
                    Entity             = $"Update Scheduling Related Tables Successful, rows added/updated = {recordsAffected}",
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Success
                };

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", updateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
Exemple #12
0
        public async Task <GenericServiceResponse> CdcEventAddressCreate(PayloadParent cdcPayload, LogCommand logCommand)
        {
            const string method           = "CdcEventAddressCreate";
            var          UpdateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter cdcPayload = {cdcPayload}";
                _logHandler.HandleLog(logCommand);

                var addressPayload = new AddressPayload(cdcPayload);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter addressPayload = {addressPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                var response = new GenericServiceResponse
                {
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                };

                Guid programGuid;
                Guid subprogramGuid;
                Guid addressTypeGuid;
                Guid countyGuid;
                Guid ownershipGuid;

                string ownershipTypeName = "Rented";

                //Customer Guid Check
                UpdateEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                if (addressPayload._PayloadHeader.CmcCustomerGuidC == null ||
                    addressPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                }

                //Address Record ID
                UpdateEventState = "Attempting To check Address Record ID Guid" + Environment.NewLine;
                if (string.IsNullOrEmpty(addressPayload._PayloadHeader.RecordIdC))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Record ID, Required for Update ");
                }

                //ProgramGuid
                UpdateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(addressPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                UpdateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(addressPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                //addressTypeGuid setting it to default for now.
                UpdateEventState = "Attempting To Get addressTypeGuid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadBody.AddressTypeC))
                {
                    var lkpAccountType = await _addressRepository.GetLKPAddressTypeFromAddressTypeName(addressPayload._PayloadBody.AddressTypeC, logCommand);

                    addressTypeGuid = lkpAccountType.AddressTypeGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing addressTypeGuid ");
                    _logHandler.HandleLog(logCommand);

                    response.Entity = "Empty Address Type";
                    return(response);
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get CountyGuid" + Environment.NewLine;
                if (addressPayload._PayloadBody.AddressTypeC.ToLower() == "service")
                {
                    if (!string.IsNullOrEmpty(addressPayload._PayloadBody.CountyC))
                    {
                        var lkpCounties = await _addressRepository.GetLkpCountyFromCountyDescription(addressPayload._PayloadBody.CountyC, logCommand);

                        countyGuid = lkpCounties.CountyGuid;
                    }

                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing CountyGuid ");
                        _logHandler.HandleLog(logCommand);

                        response.Entity = "Empty County";
                        return(response);
                    }
                }
                else
                {
                    countyGuid = Guid.Parse("24C3CDAC-2BB8-46A9-AF92-70E36D0B37F7");
                }

                //OwnershipGuid setting it to default for now.
                UpdateEventState = "Attempting To Get OwnershipGuid" + Environment.NewLine;
                if (ownershipTypeName == "Rented")
                {
                    var lkpOwnership = await _addressRepository.GetLkpOwnershipFromOwnershipType("Rented", logCommand);

                    ownershipGuid = lkpOwnership.OwnershipGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing OwnershipGuid ");
                    _logHandler.HandleLog(logCommand);
                }

                UpdateEventState = "Attempting To Build Object" + Environment.NewLine;
                var address = new Address(addressPayload, addressTypeGuid, countyGuid, ownershipGuid);

                //Update Phone
                UpdateEventState = "Attempting To Insert/Update" + Environment.NewLine;
                if (addressPayload._PayloadBody.Address_SourceC.ToLower() == "program")
                {
                    recordsAffected += await _addressRepository.UpdateProgramServiceAddress(address, logCommand);

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Update Address Complete. Rows updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity = $"Failure - Could not find Record for update, {recordsAffected}. " +
                                     $"Records Affected with required fields: " +
                                     $"-- Customer Guid: {addressPayload._PayloadBody.CmcCustomerGuidC} " +
                                     $"-- Address Source: {addressPayload._PayloadBody.Address_SourceC} " +
                                     $"-- Address Type: {addressPayload._PayloadBody.AddressTypeC} " +
                                     $"-- AddressTypeGuid: {addressTypeGuid} ",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                }
                else
                {
                    recordsAffected += await _addressRepository.InsertAddress(address, logCommand);

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Insert Address Related Tables Successful, rows added/updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Error
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Failure - Could not insert into Address Table",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Error
                        };
                    }
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", UpdateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
Exemple #13
0
        public async Task <GenericServiceResponse> CdcEventAddressUpdate(PayloadParent PayloadResponse, LogCommand logCommand)
        {
            const string method           = "UpdateLeadFromUpdateEvent";
            var          UpdateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter PayloadResponse = {PayloadResponse}";
                _logHandler.HandleLog(logCommand);

                var addressPayload = new AddressPayload(PayloadResponse);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter addressPayload = {addressPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                var response = new GenericServiceResponse
                {
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                };

                Guid programGuid;
                Guid subprogramGuid;
                Guid addressTypeGuid;
                Guid countyGuid;
                Guid ownershipGuid;

                string ownershipTypeName = "Rented";
                //Customer Guid Check
                UpdateEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                if (addressPayload._PayloadHeader.CmcCustomerGuidC == null ||
                    addressPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                }

                //Address Record ID
                UpdateEventState = "Attempting To check Address Record ID Guid" + Environment.NewLine;
                if (string.IsNullOrEmpty(addressPayload._PayloadHeader.RecordIdC))
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Record ID, Required for Update ");
                }

                //ProgramGuid
                UpdateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(addressPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                UpdateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(addressPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                //addressTypeGuid setting it to default for now.
                UpdateEventState = "Attempting To Get addressTypeGuid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(addressPayload._PayloadBody.AddressTypeC))
                {
                    var lkpAccountType = await _addressRepository.GetLKPAddressTypeFromAddressTypeName(addressPayload._PayloadBody.AddressTypeC, logCommand);

                    addressTypeGuid = lkpAccountType.AddressTypeGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing addressTypeGuid ");
                    _logHandler.HandleLog(logCommand);

                    return(response);
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get CountyGuid" + Environment.NewLine;
                if (addressPayload._PayloadBody.AddressTypeC.ToLower() == "service")
                {
                    if (!string.IsNullOrEmpty(addressPayload._PayloadBody.CountyC))
                    {
                        var lkpCounties = await _addressRepository.GetLkpCountyFromCountyDescription(addressPayload._PayloadBody.CountyC, logCommand);

                        countyGuid = lkpCounties.CountyGuid;
                    }

                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing CountyGuid ");
                        _logHandler.HandleLog(logCommand);
                        return(response);
                    }
                }
                else
                {
                    countyGuid = Guid.Parse("24C3CDAC-2BB8-46A9-AF92-70E36D0B37F7");
                }

                //CountyGuid setting it to default for now.
                UpdateEventState = "Attempting To Get OwnershipGuid" + Environment.NewLine;
                if (ownershipTypeName == "Rented")
                {
                    var lkpOwnership = await _addressRepository.GetLkpOwnershipFromOwnershipType("Rented", logCommand);

                    ownershipGuid = lkpOwnership.OwnershipGuid;
                }
                else
                {
                    logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing OwnershipGuid ");
                    _logHandler.HandleLog(logCommand);
                }

                var address = new Address(addressPayload, addressTypeGuid, countyGuid, ownershipGuid);

                //Even though this is an address update PE message, it may be the initial insert of a landlord mailing address
                if (addressTypeGuid == Guid.Parse("431407C6-C889-48BF-9DFC-7CD879F85847")) //Landlord Mailing
                {
                    var existingLlAddress = await _addressRepository.GetAddressBySfIdAndAddressType(address, logCommand);

                    if (!existingLlAddress.Any())
                    {
                        recordsAffected += await _addressRepository.InsertAddress(address, logCommand);
                    }
                    else
                    {
                        //Update Address
                        recordsAffected += await _addressRepository.UpdateAddress(address, logCommand);
                    }

                    if (recordsAffected > 0)
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Update Address Related Tables Successful, rows added/updated = {recordsAffected}",
                            Success            = true,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                    else
                    {
                        response = new GenericServiceResponse
                        {
                            Entity             = $"Address Does not Exist. Records Changed: {recordsAffected}. Could not update. ",
                            Success            = false,
                            RestResponseStatus = GenericServiceResponse.RestStatus.Success
                        };
                    }
                }

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", UpdateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
        public async Task <GenericServiceResponse> UpsertLeadFromInsertEvent(PayloadParent cdcResponseObject, LogCommand logCommand)
        {
            const string method           = "UpsertLeadFromInsertEvent";
            string       upsertEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter CDCResponseObject = {cdcResponseObject}";
                _logHandler.HandleLog(logCommand);

                var checkIfExists = await _leadRepository.GetLeads(cdcResponseObject.CmcCustomerGuidC, logCommand);

                var leadPayload = new LeadPayload(cdcResponseObject);

                var    recordsAffected = 0;
                string entityResponse;

                ServiceResponse = new GenericServiceResponse
                {
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Empty
                };

                if (checkIfExists.Any())
                {
                    recordsAffected = await _leadRepository.LeadCreatedSetRecordId(
                        leadPayload._PayloadHeader.CmcCustomerGuidC, leadPayload._PayloadHeader.RecordIdC, logCommand);

                    entityResponse = $"Lead Exists, Update SF-Record-ID, rows added/updated = {recordsAffected}" + Environment.NewLine +
                                     $"Records Expected: 1 ";
                }
                else
                {
                    Guid programGuid;
                    Guid subprogramGuid;
                    Guid lkpLeadStatusGuid;
                    Guid lkpAuditTypeGuid;
                    Guid accountTypeGuid;

                    //Customer Guid Check
                    upsertEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                    if (leadPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                    {
                        throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                    }

                    //ProgramGuid
                    upsertEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                    if (!string.IsNullOrEmpty(leadPayload._PayloadHeader.SalesforceProgramIDC))
                    {
                        var program = await _programRepository.GetProgramFromSFID(leadPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                        programGuid = program.ProgramGuid;
                    }
                    else
                    {
                        throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                    }

                    //SubprogramGuid
                    upsertEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                    if (!string.IsNullOrEmpty(leadPayload._PayloadHeader.SalesforceSubProgramIDC))
                    {
                        var subprogram = await _programRepository.GetSubProgramSFID(leadPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                        subprogramGuid = subprogram.SubProgramGuid;
                    }
                    else
                    {
                        subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                    }

                    //LKPLeadStatusGuid
                    upsertEventState = "Attempting To Get LKPLeadStatus Guid" + Environment.NewLine;
                    if (!string.IsNullOrEmpty(leadPayload._PayloadBody.Status))
                    {
                        var lkPleadStatus = await _leadRepository.GetLkpLeadStatusFromName(leadPayload._PayloadBody.Status, logCommand);

                        lkpLeadStatusGuid = lkPleadStatus.LeadStatusGuid;
                    }
                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing LKPLeadStatus ");
                        _logHandler.HandleLog(logCommand);

                        return(ServiceResponse);
                    }

                    //LKPAuditTypeGuid
                    upsertEventState = "Attempting To Get LKPAuditType Guid" + Environment.NewLine;
                    if (!string.IsNullOrEmpty(leadPayload._PayloadBody.AuditTypeC))
                    {
                        var lkpAuditType = await _leadRepository.GetLkpLeadAuditTypeFromName(leadPayload._PayloadBody.AuditTypeC, logCommand);

                        lkpAuditTypeGuid = lkpAuditType.AuditTypeGuid;
                    }
                    else
                    {
                        var lkpAuditType = await _leadRepository.GetLkpLeadAuditTypeFromName("Not Qualified", logCommand);

                        lkpAuditTypeGuid = lkpAuditType.AuditTypeGuid;
                    }

                    //LKPAccountTypeGuid
                    //Todo This is hard coded!!! NotQualify, needs to be fixed.
                    upsertEventState = "Attempting To Get LkpAccountType Guid" + Environment.NewLine;
                    if (!string.IsNullOrEmpty("Commercial"))
                    {
                        var lkpAccountType = await _customerRepository.GetCustomerAccountTypeFromName("Commercial", logCommand);

                        accountTypeGuid = lkpAccountType.AccountTypeGuid;
                    }
                    else
                    {
                        logCommand.LogMessage = string.Format($"Error: {Service}.{method} -- Missing AccountTypeGuid ");
                        _logHandler.HandleLog(logCommand);


                        return(ServiceResponse);
                    }

                    upsertEventState = "Attempting To Instantiate Customer" + Environment.NewLine;
                    var customer = new Customer(leadPayload, programGuid, subprogramGuid, accountTypeGuid);
                    upsertEventState = "Attempting To Instantiate Lead" + Environment.NewLine;
                    var lead = new Lead(leadPayload, lkpLeadStatusGuid, lkpAuditTypeGuid)
                    {
                        LeadStatusChangeDate = DateTime.Now
                    };

                    upsertEventState = "Attempting To Execute on Customer" + Environment.NewLine;
                    recordsAffected += await _customerRepository.InsertCustomer(customer, logCommand);

                    ServiceResponse = await InsertAuditRecordAsync(logCommand, cdcResponseObject, customer.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                    if (!ServiceResponse.Success)
                    {
                        return(ServiceResponse);
                    }

                    upsertEventState = "Attempting To Execute on Lead" + Environment.NewLine;
                    recordsAffected += await _leadRepository.InsertLead(lead, logCommand);

                    ServiceResponse = await InsertAuditRecordAsync(logCommand, cdcResponseObject, lead.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                    if (!ServiceResponse.Success)
                    {
                        return(ServiceResponse);
                    }

                    upsertEventState = "Attempting To Instantiate Contact" + Environment.NewLine;
                    var primaryContact = new Contact(leadPayload, Guid.Parse("BEF01936-5D80-471D-AF77-4CC2AE5161B4"));
                    recordsAffected += await _contactRepository.InsertContact(primaryContact, logCommand);

                    ServiceResponse = await InsertAuditRecordAsync(logCommand, cdcResponseObject, primaryContact.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                    if (!ServiceResponse.Success)
                    {
                        return(ServiceResponse);
                    }

                    upsertEventState = "Attempting To Get Primary Contact" + Environment.NewLine;
                    var primaryContactData = await _contactRepository.GetPrimaryContactFromCustomerGuid(primaryContact.CustomerGuid, logCommand);

                    upsertEventState = "Attempting To Instantiate Phone" + Environment.NewLine;
                    var phone = new PhoneNumbers(leadPayload, primaryContactData.ContactGuid);
                    upsertEventState = "Attempting To Instantiate Email" + Environment.NewLine;
                    var email = new Email(leadPayload, primaryContactData.ContactGuid);

                    upsertEventState = "Attempting To Execute on Phone" + Environment.NewLine;
                    recordsAffected += await _contactRepository.InsertPhone(phone, logCommand);

                    ServiceResponse = await InsertAuditRecordAsync(logCommand, cdcResponseObject, phone.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                    if (!ServiceResponse.Success)
                    {
                        return(ServiceResponse);
                    }

                    upsertEventState = "Attempting To Execute on Email" + Environment.NewLine;
                    recordsAffected += await _contactRepository.InsertEmail(email, logCommand);

                    ServiceResponse = await InsertAuditRecordAsync(logCommand, cdcResponseObject, email.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                    if (!ServiceResponse.Success)
                    {
                        return(ServiceResponse);
                    }
                    upsertEventState = "Executions Complete" + Environment.NewLine;

                    entityResponse = $"Lead Does Not Exist, Insert Skeleton " + Environment.NewLine +
                                     $"Records Inserted: {recordsAffected} " + Environment.NewLine +
                                     $"Records Expected: 5 ";
                }

                if (recordsAffected == 0)
                {
                    return(ServiceHelper.SetGenericServiceResponseForEntity($"Insert for ObjectName: {cdcResponseObject.ObjectNameC} and RecordId: {cdcResponseObject.RecordIdC} failed."));
                }
                ServiceResponse.Entity             = entityResponse;
                ServiceResponse.Success            = true;
                ServiceResponse.RestResponseStatus = GenericServiceResponse.RestStatus.Success;


                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", upsertEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
        public async Task <GenericServiceResponse> UpdateLeadFromUpdateEvent(PayloadParent payloadResponse, LogCommand logCommand)
        {
            const string method           = "UpdateLeadFromUpdateEvent";
            var          updateEventState = string.Empty;

            try
            {
                logCommand.LogMessage = $"{Service}.{method} Starting input parameter PayloadResponse = {payloadResponse}";
                _logHandler.HandleLog(logCommand);


                var leadPayload = new LeadPayload(payloadResponse);

                logCommand.LogMessage = $"{Service}.{method} Starting input parameter LeadPayload = {leadPayload}";
                _logHandler.HandleLog(logCommand);
                var recordsAffected = 0;

                var existingLeadEnumerable = await _leadRepository.GetLeadByCustomerGuidAsync(leadPayload._PayloadHeader.CmcCustomerGuidC, logCommand);

                var existingLeadList = existingLeadEnumerable.ToList();
                if (!existingLeadList.Any())
                {
                    throw new Exception($"Attempting to update Lead where CustomerGuid =  {leadPayload._PayloadHeader.CmcCustomerGuidC} but lead was not found ");
                }
                var existingLead = existingLeadList[0];

                Guid programGuid;
                Guid subprogramGuid;
                Guid lkpLeadStatusGuid;
                Guid lkpAuditTypeGuid;
                Guid accountTypeGuid;

                //Customer Guid Check
                updateEventState = "Attempting to check CustomerGuid" + Environment.NewLine;
                if (leadPayload._PayloadHeader.CmcCustomerGuidC == Guid.Empty)
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing Customer Guid ");
                }

                //ProgramGuid
                updateEventState = "Attempting To Get Program Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(leadPayload._PayloadHeader.SalesforceProgramIDC))
                {
                    var program = await _programRepository.GetProgramFromSFID(leadPayload._PayloadHeader.SalesforceProgramIDC, logCommand);

                    programGuid = program.ProgramGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing SalesforceProgramID ");
                }

                //SubprogramGuid
                updateEventState = "Attempting To Get SubProgram Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(leadPayload._PayloadHeader.SalesforceSubProgramIDC))
                {
                    var subprogram = await _programRepository.GetSubProgramSFID(leadPayload._PayloadHeader.SalesforceSubProgramIDC, logCommand);

                    subprogramGuid = subprogram.SubProgramGuid;
                }
                else
                {
                    subprogramGuid = Guid.Parse("FB02657F-3985-4F06-84C3-1669BE2F2991");
                }

                //LKPLeadStatusGuid
                updateEventState = "Attempting To Get LKPLeadStatus Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(leadPayload._PayloadBody.Status))
                {
                    var lkPleadStatus = await _leadRepository.GetLkpLeadStatusFromName(leadPayload._PayloadBody.Status, logCommand);

                    lkpLeadStatusGuid = lkPleadStatus.LeadStatusGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing LKPLeadStatus ");
                }

                //LKPAuditTypeGuid
                updateEventState = "Attempting To Get LKPAuditType Guid" + Environment.NewLine;
                if (!string.IsNullOrEmpty(leadPayload._PayloadBody.AuditTypeC))
                {
                    var lkpAuditType = await _leadRepository.GetLkpLeadAuditTypeFromName(leadPayload._PayloadBody.AuditTypeC, logCommand);

                    lkpAuditTypeGuid = lkpAuditType.AuditTypeGuid;
                }
                else
                {
                    throw new Exception($"Error: {Service}.{method} -- Missing LKPAuditType ");
                }

                updateEventState = "Attempting To Instantiate customer" + Environment.NewLine;
                var customer = new Customer(leadPayload, programGuid, subprogramGuid, accountTypeGuid);

                //Get Primary Contact Guid
                updateEventState = "Attempting To Instantiate primaryContact" + Environment.NewLine;
                var primaryContact = new Contact(leadPayload, Guid.Parse("BEF01936-5D80-471D-AF77-4CC2AE5161B4"));
                //primaryContact.CustomerGuid = Guid.Parse("A30FD8B1-9BE2-47FB-8D9E-AC8EFCEFE369");

                updateEventState = "Attempting To Get Primary Contact" + Environment.NewLine;
                var primaryContactData = await _contactRepository.GetPrimaryContactFromCustomerGuid(leadPayload._PayloadHeader.CmcCustomerGuidC, logCommand);


                //Customer
                updateEventState = "Attempting To Execute on Customer" + Environment.NewLine;
                recordsAffected += await _customerRepository.UpdateCustomer(customer, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, payloadResponse, customer.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                //Lead
                updateEventState = "Attempting To Instantiate lead" + Environment.NewLine;
                var lead = new Lead(leadPayload, lkpLeadStatusGuid, lkpAuditTypeGuid);

                //Update Lead Status Change Date timestamp if lead status changed
                if (existingLead.LeadStatusGuid == lead.LeadStatusGuid)
                {
                    if (lead.LeadStatusChangeDate == null)
                    {
                        lead.LeadStatusChangeDate = Convert.ToDateTime("1900-01-01");
                    }
                }
                else
                {
                    lead.LeadStatusChangeDate = DateTime.Now.Date;
                }

                //Set ReserveDate to Today.23:59.59 if reservation is done by SF.  See GetPrioLeads which sets
                //Reservation for leads to now + 15 minutes as a way to send different sets of leads to CSR's
                //that are looking for leads with similar criteria
                if (lead.ReservedDate == DateTime.Today)
                {
                    lead.ReservedDate = DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59);
                }

                updateEventState = "Attempting To Execute on Lead" + Environment.NewLine;
                recordsAffected += await _leadRepository.UpdateLeadAsync(lead, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, payloadResponse, lead.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                //Update Primary Contact
                updateEventState = "Attempting To Execute on Primary Contact" + Environment.NewLine;
                recordsAffected += await _contactRepository.UpdatePrimaryContact(primaryContact, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, payloadResponse, primaryContact.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                //Phone and Email
                updateEventState = "Attempting To Instantiate Phone and Email Objects" + Environment.NewLine;
                var phone = new PhoneNumbers(leadPayload, primaryContactData.ContactGuid);
                var email = new Email(leadPayload, primaryContactData.ContactGuid);

                updateEventState = "Attempting To Execute on Phone" + Environment.NewLine;
                recordsAffected += await _contactRepository.UpdatePhone(phone, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, payloadResponse, phone.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                updateEventState = "Attempting To Execute on Email" + Environment.NewLine;
                recordsAffected += await _contactRepository.UpdateEmail(email, logCommand);

                ServiceResponse = await InsertAuditRecordAsync(logCommand, payloadResponse, email.GetType().FullName, leadPayload._PayloadBody.LastModifiedById);

                if (!ServiceResponse.Success)
                {
                    return(ServiceResponse);
                }

                updateEventState = "Executions Complete" + Environment.NewLine;


                ServiceResponse = new GenericServiceResponse
                {
                    Entity             = $"Update Lead Related Tables Successful, rows added/updated = {recordsAffected}",
                    Success            = true,
                    RestResponseStatus = GenericServiceResponse.RestStatus.Success
                };

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(ServiceResponse);
            }
            catch (Exception ex)
            {
                ex.Data.Add("Point of Failure", updateEventState);
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }
        public async Task <GenericServiceResponse> GetLeadDetailed(Guid customerGuid, LogCommand logCommand)
        {
            const string method = "GetLeadDetailed";

            try
            {
                logCommand.LogMessage = string.Format($"{Service}.{method} Starting input parameter leadGuid = {0}", customerGuid);
                _logHandler.HandleLog(logCommand);

                //Initialize Detailed Object, Get Lead Data.
                var sfLead = new SFDetailedLead
                {
                    LeadData     = await _leadRepository.GetDetailedLead(customerGuid, logCommand),
                    CustomerData = await _customerRepository.GetDetailedCustomerFromGuid(customerGuid, logCommand),
                    CapStatus    = await _usageRepository.GetIsCapQualifiedFromCustomerGuid(customerGuid, logCommand),

                    PremiseData = new List <SFDetailedPremise>()
                    {
                        new SFDetailedPremise()
                        {
                            AddressData =
                                await _addressRepository.GetDetailedAddressFromCustomerGuid(customerGuid, logCommand)
                        }
                    },

                    UsageData          = await _usageRepository.GetUsageFromCustomerGuid(customerGuid, logCommand),
                    PrimaryContactData = new SFDetailedContact()
                    {
                        ContactData = await _contactRepository.GetPrimaryContactFromCustomerGuid(customerGuid,
                                                                                                 logCommand)
                    }
                };

                // Primary Contact Data: Phones, Emails, MailingAddresses
                sfLead.PrimaryContactData.ContactPhones = await _contactRepository.GetPhoneFromContactGuid(sfLead.PrimaryContactData.ContactData.ContactGuid, logCommand);

                sfLead.PrimaryContactData.ContactEmails = await _contactRepository.GetEmailFromContactGuid(sfLead.PrimaryContactData.ContactData.ContactGuid, logCommand);

                //--------------------------------------------------------

                //Only Send Data On Initial Load.
                if (string.IsNullOrEmpty(sfLead.LeadData.SFLeadID))
                {
                    sfLead.ERMSData = await _ermsRepository.GetERMSCustomer(customerGuid, logCommand);
                }
                else
                {
                    sfLead.ERMSData = new ERMSCustomer();
                }

                var response = ServiceHelper.SetGenericServiceResponseForEntity(sfLead);
                response.Success = true;

                logCommand.LogMessage = string.Format($"{Service}.{method} completed");
                _logHandler.HandleLog(logCommand);

                return(response);
            }
            catch (Exception ex)
            {
                AppLogger.LogException(_loggingInstance, ex.Message, ex);
                return(ServiceHelper.SetErrorGenericServiceResponse(ex));
            }
        }