/// <summary> /// Delete legal unit method (when revise on data source queue page), deletes unit from database /// </summary> /// <param name="statId">Id of stat unit</param> /// <param name="userId">Id of user for edit unit if there is history</param> /// <param name="dataUploadTime">data source upload time</param> public async Task <bool> DeleteLegalUnitFromDb(string statId, string userId, DateTime?dataUploadTime) { var unit = _dbContext.LegalUnits.AsNoTracking() .Include(x => x.PersonsUnits) .Include(x => x.ActivitiesUnits) .Include(x => x.Address) .Include(x => x.PostalAddress) .Include(x => x.ActualAddress) .FirstOrDefault(legU => legU.StatId == statId); if (unit == null || dataUploadTime == null || string.IsNullOrEmpty(userId)) { return(false); } var afterUploadLegalUnitsList = _dbContext.LegalUnitHistory .Include(x => x.PersonsUnits) .Include(x => x.ActivitiesUnits) .Include(x => x.ForeignParticipationCountriesUnits) .Include(x => x.Address) .Include(x => x.PostalAddress) .Include(x => x.ActualAddress) .Where(legU => legU.ParentId == unit.RegId && legU.StartPeriod >= dataUploadTime).OrderBy(legU => legU.StartPeriod).ToList(); var beforeUploadLegalUnitsList = _dbContext.LegalUnitHistory .Include(x => x.PersonsUnits) .Include(x => x.ActivitiesUnits) .Include(x => x.ForeignParticipationCountriesUnits) .Include(x => x.Address) .Include(x => x.PostalAddress) .Include(x => x.ActualAddress) .Where(legU => legU.ParentId == unit.RegId && legU.StartPeriod < dataUploadTime).OrderBy(legU => legU.StartPeriod).ToList(); if (afterUploadLegalUnitsList.Count > 0) { return(false); } if (beforeUploadLegalUnitsList.Count > 0) { await UpdateUnitTask(unit, beforeUploadLegalUnitsList.Last(), userId, StatUnitTypes.LegalUnit); _dbContext.LegalUnitHistory.Remove(beforeUploadLegalUnitsList.Last()); await _dbContext.SaveChangesAsync(); } else { var localUnitDeleted = await DeleteLocalUnitFromDb(statId, userId, dataUploadTime); LocalUnit local = null; if (!localUnitDeleted) { local = await _dbContext.LocalUnits.FirstOrDefaultAsync(x => x.LegalUnitId == unit.RegId); if (local != null) { local.LegalFormId = null; } } _dbContext.LegalUnits.Remove(unit); await _dbContext.SaveChangesAsync(); await _elasticService.DeleteDocumentAsync(Mapper.Map <IStatisticalUnit, ElasticStatUnit>(unit)); if (local != null) { await _elasticService.EditDocument(Mapper.Map <IStatisticalUnit, ElasticStatUnit>(local)); _commonSvc.TrackUnithistoryFor <LocalUnit>(local.RegId, userId, ChangeReasons.Edit, "Link to Legal Unit deleted by data source upload service reject functionality", DateTime.Now); } await DeleteEnterpriseUnitFromDb(statId, userId, dataUploadTime); } return(true); }