//function that directly updates our Staging table in DB
        private Staging FillStagingIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink,
                                              SyncSystemDTO syncSystem, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            if (!CheckChangeLog(jiraRequest, syncSystemFieldMappings))
            {
                return(null);
            }

            logger.Info("WebHookReceiver Staging");
            if (jiraRequest.WebhookEvent == "jira:issue_deleted")
            {
                return(null);
            }

            var staging = new Staging
            {
                RecordDateCreated = DateTime.Now,
                SystemId          = syncSystem.SystemId,
                RecordDateUpdated = DateTime.Now,
                RecordState       = RecordStateConst.New,
                WebHookEvent      = jiraRequest.WebhookEvent,
                ProjectId         = jiraRequest.Issue.Fields.Project.Id,
                ProjectKey        = jiraRequest.Issue.Fields.Project.Key,
                ProjectName       = jiraRequest.Issue.Fields.Project.Name,
                IssueId           = jiraRequest.Issue.Id,
                IssueKey          = jiraRequest.Issue.Key,
                IssueTypeId       = jiraRequest.Issue.Fields.IssueType.Id,
                IssueTypeName     = jiraRequest.Issue.Fields.IssueType.Name,
                IsSubTask         = jiraRequest.Issue.Fields.IssueType.Subtask,
                IssueName         = GetIssueName(jiraRequest),
                ParentEpicKey     = jiraEpicLink,
                //ParentIssueKey = jiraEpicLink,
                OriginalEstimate = jiraRequest.Issue.Fields.TimeOriginalEstimate,
                IssueActualWork  = jiraRequest.Issue.Fields.TimeSpent,
                IssueStatus      = jiraRequest.Issue.Fields.Status.Name,
                DateStart        = jiraRequest.Issue.Fields.Created
            };

            GetChangedFields(jiraRequest.ChangeLog?.Items, staging);
            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                staging.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                staging.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                staging.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                staging.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                staging.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                staging.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                staging.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            systemToDbViewModel.StagingsToInsert.Add(staging);
            return(staging);
        }
 public List <string> GetEpicsToIgnore(Guid projectUid, string projectId, SyncSystemDTO syncSystem)
 {
     return(UnitOfWork.ProjectServerSystemLinkRepository
            .GetQuery(x => x.ProjectUid != projectUid &&
                      !String.IsNullOrEmpty(x.EpicKey) &&
                      x.SystemId == syncSystem.SystemId &&
                      x.ProjectId == projectId)
            .Select(x => x.EpicKey)
            .ToList());
 }
        public JiraAccessService(SyncSystemDTO syncSystem)
        {
            SyncSystem   = syncSystem;
            jiraUserName = syncSystem.SystemLogin;
            jiraPassword = syncSystem.SystemPassword;
            jiraApiUrl   = syncSystem.SystemApiUrl.Trim('/');
            JiraRestClientSettings jiraRestClientSettings = new JiraRestClientSettings();

            jiraRestClientSettings.CustomFieldSerializers.Remove("com.pyxis.greenhopper.jira:gh-sprint");
            JiraConnection = Atlassian.Jira.Jira.CreateRestClient(syncSystem.SystemUrl, jiraUserName, jiraPassword, jiraRestClientSettings);
        }
        public async Task <ProxyResponse> Execute(int systemId, int itemId, string projectId)
        {
            SystemToDbViewModel syncAllViewModel = new SystemToDbViewModel();

            SyncSystemDTO syncSystem = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(syncSystem.SystemId);

            VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"),
                                                         new VssBasicCredential(String.Empty, syncSystem.SystemPassword));
            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            List <WorkItem> epics = new List <WorkItem>();

            if (itemId == 0)
            {
                Wiql wiQuery = new Wiql()
                {
                    Query =
                        "Select [System.Id] "
                        + "from WorkItems"
                        + " Where [System.WorkItemType] = 'Epic'"
                        + $" And [System.TeamProject] = '{projectId}'"
                };
                var items = await witClient.QueryByWiqlAsync(wiQuery);

                List <int>      epicsIds    = items.WorkItems.Select(x => x.Id).ToList();
                List <WorkItem> masterItems = await witClient.GetWorkItemsAsync(epicsIds, expand : WorkItemExpand.Relations);

                epics.AddRange(masterItems);
            }
            else
            {
                WorkItem masterItem = await witClient.GetWorkItemAsync(itemId, expand : WorkItemExpand.Relations);

                epics.Add(masterItem);
            }



            await GetDataFromTfs(syncAllViewModel, epics, systemId, syncSystemFieldMappings, witClient);

            await commonBusinessService.AddNewData(syncAllViewModel);

            commonBusinessService.DeleteOldData(syncAllViewModel, syncSystem.SystemId);

            return(new ProxyResponse
            {
                Result = "ok",
                Data = "TFS Execute OK"
            });
        }
        public async Task <JsonResult> ExecuteRequest([FromBody] JiraProxyRequest jiraRequest)
        {
            if (jiraRequest.SystemId == null)
            {
                return(Json(new ProxyResponse
                {
                    Result = "ko",
                    Data = "System Id is null"
                }, JsonRequestBehavior.AllowGet));
            }
            try
            {
                string        response   = null;
                SyncSystemDTO syncSystem = await SyncSystemBusinessService.GetSyncSystemAsync(jiraRequest.SystemId.Value);

                if (syncSystem != null)
                {
                    JiraAccessService jiraAccessService = new JiraAccessService(syncSystem);
                    response = await jiraAccessService.GetJiraResponse(jiraRequest);
                }
                if (String.IsNullOrEmpty(response))
                {
                    return(Json(new ProxyResponse
                    {
                        Result = "ko",
                        Data = "Jira Response is empty"
                    }, JsonRequestBehavior.AllowGet));
                }
                JsonResult jsonResult = Json(new ProxyResponse
                {
                    Result = "ok",
                    Data   = response
                }, JsonRequestBehavior.AllowGet);
                jsonResult.MaxJsonLength = Int32.MaxValue;
                return(jsonResult);
            }
            catch (Exception exception)
            {
                return(HandleException(exception));
            }
        }
        public async Task <ProxyResponse> AddWebhookToDataBase(string jsonWebhook, int systemId)
        {
            Dictionary <string, object> commonDictionary    = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonWebhook);
            SystemToDbViewModel         systemToDbViewModel = new SystemToDbViewModel();

            logger.Info("WebHookReceiver UnitOfWork");
            int?id = 0;

            switch (commonDictionary[FieldEventType].ToString())
            {
            case "workitem.created":
                var webHookCreateRequest = JsonConvert.DeserializeObject <WebHookCreateRequest>(jsonWebhook);
                id = webHookCreateRequest.Resource?.Id;
                break;

            case "workitem.updated":
                var webHookUpdateRequest = JsonConvert.DeserializeObject <WebHookUpdateRequest>(jsonWebhook);
                id = webHookUpdateRequest.Resource?.WorkItemId;
                break;
            }
            SyncSystemDTO syncSystem = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            if (syncSystem == null || !id.HasValue || id == 0)
            {
                //await FillWebHookEntryAsync(unitOfWork, result);
                logger.Info("System not found " + systemId);
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }

            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(systemId);

            //string.Empty, syncSystem.SystemPassword
            //VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"), new VssCredentials());

            VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"),
                                                         new VssBasicCredential(String.Empty, syncSystem.SystemPassword));

            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WIT.WorkItemTrackingHttpClient witClient = connection.GetClient <WIT.WorkItemTrackingHttpClient>();
            WorkItem workItem = await witClient.GetWorkItemAsync(id.Value, expand : WorkItemExpand.Relations);

            //DbContextTransaction transaction = unitOfWork.BeginTransaction();
            try
            {
                #region Staging

                var staging = new Staging
                {
                    RecordDateCreated = DateTime.Now,
                    SystemId          = systemId,
                    ChangedFields     = "all",
                    RecordDateUpdated = DateTime.Now,
                    RecordState       = RecordStateConst.New,
                    WebHookEvent      = commonDictionary[FieldEventType].ToString()
                };

                if (workItem.Fields.ContainsKey("System.TeamProject"))
                {
                    staging.ProjectId   = (string)workItem.Fields["System.TeamProject"];
                    staging.ProjectKey  = (string)workItem.Fields["System.TeamProject"];
                    staging.ProjectName = (string)workItem.Fields["System.TeamProject"];
                }
                staging.IssueId  = workItem.Id?.ToString();
                staging.IssueKey = workItem.Id?.ToString();
                if (workItem.Fields.ContainsKey("System.WorkItemType"))
                {
                    staging.IssueTypeId   = workItem.Fields["System.WorkItemType"].ToString();
                    staging.IssueTypeName = workItem.Fields["System.WorkItemType"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.Title"))
                {
                    staging.IssueName = workItem.Fields["System.Title"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.IterationId"))
                {
                    staging.ParentVersionId = workItem.Fields["System.IterationId"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.IterationLevel2"))
                {
                    staging.ParentVersionName = workItem.Fields["System.IterationLevel2"].ToString();
                }
                if (workItem.Fields.ContainsKey(FieldAssignedTo))
                {
                    if (workItem.Fields[FieldAssignedTo] != null)
                    {
                        staging.Assignee = workItem.Fields[FieldAssignedTo].ToString()
                                           .Substring(workItem.Fields[FieldAssignedTo].ToString()
                                                      .IndexOf("<", StringComparison.Ordinal)).Trim('<', '>');
                    }
                }
                if (workItem.Relations != null)
                {
                    WorkItemRelation relationCrt = workItem.Relations
                                                   .FirstOrDefault(x => x.Rel == "System.LinkTypes.Hierarchy-Reverse");
                    if (relationCrt != null)
                    {
                        if (workItem.Fields["System.WorkItemType"].ToString().ToLower().Equals("feature"))
                        {
                            staging.ParentEpicId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                            staging.ParentEpicKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        }
                        else
                        {
                            staging.ParentIssueId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                            staging.ParentIssueKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        }
                    }
                    else
                    {
                        staging.ParentIssueId  = null;
                        staging.ParentIssueKey = null;
                    }
                }
                systemToDbViewModel.StagingsToInsert.Add(staging);
                //FillStagingWorklog(unitOfWork, staging, workItem, systemId);

                SyncSystemFieldMapping fieldMappingRecordStateGeneral = syncSystemFieldMappings
                                                                        .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                        x.EpmFieldName == ProjectServerConstants.RecordStateGeneral);

                if (fieldMappingRecordStateGeneral != null)
                {
                    var stagingFieldMappingValueGeneral = new StagingFieldMappingValue
                    {
                        Staging = staging,
                        SyncSystemFieldMappingId = fieldMappingRecordStateGeneral.SyncSystemFieldMappingId,
                        Value = RecordStateConst.New
                    };
                    systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingFieldMappingValueGeneral);
                }

                SyncSystemFieldMapping fieldMappingRecordStateActual = syncSystemFieldMappings
                                                                       .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                       x.EpmFieldName == ProjectServerConstants.RecordStateActual);

                if (fieldMappingRecordStateActual != null)
                {
                    var stagingFieldMappingValueActual = new StagingFieldMappingValue
                    {
                        Staging = staging,
                        SyncSystemFieldMappingId = fieldMappingRecordStateActual.SyncSystemFieldMappingId,
                        Value = RecordStateConst.Done
                    };
                    systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingFieldMappingValueActual);
                }

                #endregion

                #region Master

                var master = masterBusinessService.GetIssueById(systemId, id.ToString(), staging.IssueTypeId);
                if (master == null)
                {
                    master = new Master
                    {
                        RecordDateCreated = DateTime.Now
                    };
                    systemToDbViewModel.MastersToInsert.Add(master);
                }

                master.RecordDateUpdated = DateTime.Now;
                master.SystemId          = systemId;

                master.IssueId   = staging.IssueId;
                master.IssueKey  = staging.IssueKey;
                master.IssueName = staging.IssueName;

                master.ProjectId   = staging.ProjectId;
                master.ProjectKey  = staging.ProjectKey;
                master.ProjectName = staging.ProjectName;

                master.IsSubTask = staging.IsSubTask;

                master.ParentVersionReleased = staging.ParentVersionReleased;
                master.IssueTypeName         = staging.IssueTypeName;
                master.IssueTypeId           = staging.IssueTypeId;
                master.DateFinish            = staging.DateFinish;
                master.DateRelease           = staging.DateRelease;

                #endregion

                #region MasterHistory

                var masterHistory = new MasterHistory
                {
                    RecordDateCreated = DateTime.Now
                };
                systemToDbViewModel.MasterHistoriesToInsert.Add(masterHistory);

                masterHistory.RecordDateUpdated = DateTime.Now;
                masterHistory.SystemId          = systemId;

                masterHistory.IssueId   = staging.IssueId;
                masterHistory.IssueKey  = staging.IssueKey;
                masterHistory.IssueName = staging.IssueName;

                masterHistory.ProjectId   = staging.ProjectId;
                masterHistory.ProjectKey  = staging.ProjectKey;
                masterHistory.ProjectName = staging.ProjectName;

                masterHistory.IsSubTask = staging.IsSubTask;

                masterHistory.ParentVersionReleased = staging.ParentVersionReleased;
                masterHistory.IssueTypeName         = staging.IssueTypeName;
                masterHistory.IssueTypeId           = staging.IssueTypeId;
                masterHistory.DateFinish            = staging.DateFinish;
                masterHistory.DateRelease           = staging.DateRelease;


                #endregion

                await commonBusinessService.AddNewData(systemToDbViewModel);

                //await unitOfWork.SaveChangesAsync();
                //unitOfWork.CommitTransaction(transaction);
            }
            //catch (DbEntityValidationException exception)
            //{
            //    logger.Fatal(exception);
            //    unitOfWork.RollbackTransaction(transaction);

            //    foreach (DbEntityValidationResult validationResult in exception.EntityValidationErrors)
            //    {
            //        foreach (DbValidationError error in validationResult.ValidationErrors)
            //        {
            //            logger.Fatal(error.PropertyName + " " + error.ErrorMessage);
            //        }
            //    }
            //}
            catch (Exception exception)
            {
                logger.Fatal(exception);
                //unitOfWork.RollbackTransaction(transaction);
            }

            logger.Info("WebHookReceiver END");
            return(new ProxyResponse
            {
                Result = "ok",
                Data = "WebHookReceiver POST"
            });
        }
        public async Task <List <Issue> > GetIssuesAsync(string jql, string updateIssueStartDate, SyncSystemDTO syncSystem)
        {
            int          itemsPerPage = 1000;
            int          counter      = 0;
            List <Issue> result       = new List <Issue>();

            if (syncSystem.ActualsStartDate.HasValue)
            {
                jql = $"({jql}) and ((updated >= {updateIssueStartDate} and issuetype != 'Epic') or issuetype = 'Epic')";
            }
            logger.Info($"GetIssuesAsync jql: {jql}");
            IPagedQueryResult <Issue> query = await JiraConnection.Issues
                                              .GetIssuesFromJqlAsync(jql, itemsPerPage, counter);

            logger.Info($"GetIssuesAsync counter: {counter}; query.TotalItems: {query.TotalItems}; " +
                        $"query.ItemsPerPage: {query.ItemsPerPage}; query.StartAt: {query.StartAt}");

            result.AddRange(query.ToList());

            counter += itemsPerPage;

            while (query.TotalItems >= counter)
            {
                logger.Info("GetIssuesAsync while1 counter " + counter);

                query = await JiraConnection.Issues
                        .GetIssuesFromJqlAsync(jql, itemsPerPage, counter);

                counter += itemsPerPage;

                logger.Info($"GetIssuesAsync while2 counter: {counter}; query.TotalItems: {query.TotalItems}; " +
                            $"query.ItemsPerPage: {query.ItemsPerPage}; query.StartAt: {query.StartAt}");

                result.AddRange(query.ToList());
            }
            logger.Info("GetIssuesAsync result.Count " + result.Count);
            return(result);
        }
        public async Task <ProxyResponse> AddWebhookToDataBase(string jsonWebhook, int systemId)
        {
            logger.Info("WebHookReceiver UnitOfWork");

            JiraAccessService jiraAccessService = null;
            SyncSystemDTO     syncSystem        = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            if (syncSystem != null)
            {
                jiraAccessService = new JiraAccessService(syncSystem);
            }
            if (jiraAccessService == null)
            {
                //await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
                logger.Error("System not found " + systemId);
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }
            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(syncSystem.SystemId);

            logger.Info("WebHookReceiver Get Fields Start");
            customFields = await jiraAccessService.GetCustomFields();

            if (customFields == null)
            {
                logger.Error("WebHookReceiver Custom fields for system " + systemId + " is NULL!");
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }
            jiraEpicLinkField = customFields.FirstOrDefault(x => x.Name == JiraConstants.EpicLinkFieldName);

            logger.Info("WebHookReceiver Get Fields End");
            JiraRequest jiraRequest  = null;
            string      jiraEpicLink = null;
            string      jiraEpicName = null;

            try
            {
                jiraRequest = JsonConvert.DeserializeObject <JiraRequest>(jsonWebhook);
                if (jiraRequest == null)
                {
                    //await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
                    logger.Info("WebHookReceiver END");
                    return(new ProxyResponse
                    {
                        Result = "ok",
                        Data = "WebHookReceiver POST"
                    });
                }
                logger.Info($"WebHookReceiver syncSystem.SystemName: {syncSystem.SystemName}; " +
                            $"jiraRequest.WebhookEvent: {jiraRequest.WebhookEvent}");

                if (jiraRequest.Issue != null)
                {
                    jiraRequest.Issue.AllFields = GetIssueFieldsDictionary(jsonWebhook);

                    if (jiraRequest.Issue.Fields.IssueType.Name != "Epic")
                    {
                        if (jiraEpicLinkField != null)
                        {
                            jiraEpicLink = (string)jiraRequest.Issue.GetField(jiraEpicLinkField.Id);
                            Master masterEpic = masterBusinessService.GetMaster(syncSystem.SystemId, jiraEpicLink);
                            if (masterEpic != null)
                            {
                                jiraEpicName = masterEpic.IssueName;
                            }
                        }
                    }
                    else
                    {
                        jiraEpicName = jiraRequest.Issue.Fields.Summary.Trim();
                    }

                    logger.Info(syncSystem.SystemName + ": " + jiraRequest.WebhookEvent
                                + "; ProjectId: " + jiraRequest.Issue.Fields.Project.Id
                                + "; ProjectKey: " + jiraRequest.Issue.Fields.Project.Key
                                + "; IssueKey: " + jiraRequest.Issue.Key
                                + "; IssueName: " + jiraRequest.Issue.Fields.Summary.Trim()
                                + "; ChangedFields: " + GetChangedFields(jiraRequest.ChangeLog?.Items));
                }
            }
            catch (Exception exception)
            {
                HandleException(exception);
            }
            jiraEpicName = jiraEpicName.RemoveNewLinesTabs().Truncate();
            //DbContextTransaction transaction = unitOfWork.BeginTransaction();
            logger.Info("WebHookReceiver DbContextTransaction");
            try
            {
                SystemToDbViewModel systemToDbViewModel = new SystemToDbViewModel();
                Staging             staging;
                MasterHistory       masterHistory;
                Master master;
                if (jiraRequest?.Issue != null)
                {
                    if (jiraRequest.WebhookEvent == "jira:issue_deleted")
                    {
                        logger.Info("WebHookReceiver END");

                        return(new ProxyResponse
                        {
                            Result = "ok",
                            Data = "WebHookReceiver POST"
                        });
                    }
                    master        = FillMasterIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem);
                    masterHistory = FillMasterHistoryIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem);
                    staging       = FillStagingIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem,
                                                          syncSystemFieldMappings);
                    FillCustomFields(systemToDbViewModel, jiraRequest, master, staging, masterHistory,
                                     syncSystemFieldMappings, jiraEpicName);

                    AddLastUpdateUser(systemToDbViewModel, jiraRequest, staging, syncSystemFieldMappings);
                    AddSprints(systemToDbViewModel, jiraRequest, jiraAccessService, master, staging, masterHistory,
                               syncSystemFieldMappings);
                }
                if (jiraRequest?.Worklog != null)
                {
                    FillWorkLog(systemToDbViewModel, jiraRequest, systemId);
                }
                if (jiraRequest?.Version != null)
                {
                    master        = FillMasterVersionAsync(systemToDbViewModel, jiraRequest, systemId);
                    masterHistory = FillMasterHistoryVersionAsync(systemToDbViewModel, jiraRequest, systemId);
                    staging       = FillStagingVersionAsync(systemToDbViewModel, jiraRequest, systemId, syncSystemFieldMappings);

                    if (staging != null)
                    {
                        SyncSystemFieldMapping fieldMappingRecordStateGeneral = syncSystemFieldMappings
                                                                                .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                                x.EpmFieldName == ProjectServerConstants.RecordStateGeneral);
                        SetCustomFields(systemToDbViewModel, fieldMappingRecordStateGeneral, master, staging, masterHistory,
                                        RecordStateConst.New, null, true);

                        SyncSystemFieldMapping fieldMappingRecordStateActual = syncSystemFieldMappings
                                                                               .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                               x.EpmFieldName == ProjectServerConstants.RecordStateActual);
                        SetCustomFields(systemToDbViewModel, fieldMappingRecordStateActual, master, staging, masterHistory,
                                        RecordStateConst.Done, null, true);
                    }
                }
                await commonBusinessService.AddNewData(systemToDbViewModel);
            }
            catch (Exception exception)
            {
                logger.Error(exception);
            }
            //catch (DbUpdateException exception)
            //{
            //    foreach (DbEntityEntry dbEntityEntry in exception.Entries)
            //    {
            //        string resultString = dbEntityEntry.CurrentValues.PropertyNames.Aggregate("",
            //            (current, propertyName) =>
            //                current +
            //                $"propertyName: {propertyName} - value: {dbEntityEntry.CurrentValues[propertyName]};");
            //        logger.Fatal(
            //            $"WebHookReceiver DbUpdateException dbEntityEntry.Entity {dbEntityEntry.Entity}; resultString: {resultString}");
            //    }
            //}
            //catch (DbEntityValidationException exception)
            //{
            //    HandleException(exception);
            //    unitOfWork.RollbackTransaction(transaction);

            //    foreach (DbEntityValidationResult validationResult in exception.EntityValidationErrors)
            //    {
            //        foreach (DbValidationError error in validationResult.ValidationErrors)
            //        {
            //            HandleException(error.PropertyName + " " + error.ErrorMessage, true);
            //        }
            //    }
            //}
            //catch (Exception exception)
            //{
            //    HandleException(exception);
            //    unitOfWork.RollbackTransaction(transaction);
            //}
            ////finally
            ////{
            ////    await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
            ////}
            return(new ProxyResponse
            {
                Result = "ok",
                Data = "WebHookReceiver POST"
            });
        }
        //function that directly updates our MasterHistory table in DB
        private MasterHistory FillMasterHistoryIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink, SyncSystemDTO syncSystem)
        {
            logger.Info("WebHookReceiver Issue MasterHistory");
            if (jiraRequest.WebhookEvent == "jira:issue_deleted")
            {
                return(null);
            }
            var masterHistory = new MasterHistory
            {
                RecordDateCreated = DateTime.Now,
                RecordDateUpdated = DateTime.Now,
                SystemId          = syncSystem.SystemId,
                ProjectId         = jiraRequest.Issue.Fields.Project.Id,
                ProjectKey        = jiraRequest.Issue.Fields.Project.Key,
                ProjectName       = jiraRequest.Issue.Fields.Project.Name,
                IssueId           = jiraRequest.Issue.Id,
                IssueKey          = jiraRequest.Issue.Key,
                IssueTypeId       = jiraRequest.Issue.Fields.IssueType.Id,
                IssueTypeName     = jiraRequest.Issue.Fields.IssueType.Name,
                IsSubTask         = jiraRequest.Issue.Fields.IssueType.Subtask,
                IssueName         = GetIssueName(jiraRequest),
                ParentEpicKey     = jiraEpicLink,
                //ParentIssueKey = jiraEpicLink,
                IssueStatus = jiraRequest.Issue.Fields.Status.Name,
                DateStart   = jiraRequest.Issue.Fields.Created
            };

            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                masterHistory.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                masterHistory.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                masterHistory.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                masterHistory.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                masterHistory.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                masterHistory.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                masterHistory.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            systemToDbViewModel.MasterHistoriesToInsert.Add(masterHistory);
            return(masterHistory);
        }
        //function that directly updates our Master table in DB
        private Master FillMasterIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink, SyncSystemDTO syncSystem)
        {
            logger.Info("WebHookReceiver Issue Master");
            Master master = masterBusinessService.GetIssueById(syncSystem.SystemId, jiraRequest.Issue.Id,
                                                               jiraRequest.Issue.Fields.IssueType.Id);

            if (jiraRequest.WebhookEvent == "jira:issue_deleted" && master != null)
            {
                systemToDbViewModel.MastersToDelete.Add(master);
                return(null);
            }
            if (master == null)
            {
                master = new Master
                {
                    RecordDateCreated = DateTime.Now
                };
                systemToDbViewModel.MastersToInsert.Add(master);
            }
            master.RecordDateUpdated = DateTime.Now;
            master.SystemId          = syncSystem.SystemId;
            master.ProjectId         = jiraRequest.Issue.Fields.Project.Id;
            master.ProjectKey        = jiraRequest.Issue.Fields.Project.Key;
            master.ProjectName       = jiraRequest.Issue.Fields.Project.Name;

            master.IssueId       = jiraRequest.Issue.Id;
            master.IssueKey      = jiraRequest.Issue.Key;
            master.IssueTypeId   = jiraRequest.Issue.Fields.IssueType.Id;
            master.IssueTypeName = jiraRequest.Issue.Fields.IssueType.Name;
            master.IsSubTask     = jiraRequest.Issue.Fields.IssueType.Subtask;
            master.IssueName     = GetIssueName(jiraRequest);
            master.ParentEpicKey = jiraEpicLink;
            //master.ParentIssueKey = jiraEpicLink;

            master.OriginalEstimate = jiraRequest.Issue.Fields.TimeOriginalEstimate;
            master.IssueActualWork  = jiraRequest.Issue.Fields.TimeSpent;
            master.DateStart        = jiraRequest.Issue.Fields.Created;

            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                master.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                master.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                master.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                master.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                master.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            master.IssueStatus = jiraRequest.Issue.Fields.Status.Name;
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                master.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                master.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            return(master);
        }