public pubblicazione GetAVCPStructure(DocumentSeriesItem item) { var docs = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainDocuments(item); if (docs.Count > 1) { throw new DocSuiteException(string.Format("Trovati {0} documenti.", docs.Count)); } if (docs == null || docs.Count == 0) { throw new DocSuiteException("Nessun documento trovato."); } var doc = docs[0]; string ss; pubblicazione result; try { ss = System.Text.Encoding.Unicode.GetString(doc.Stream); result = XmlUtil.Deserialize <pubblicazione>(ss); } catch (Exception) { ss = System.Text.Encoding.UTF8.GetString(doc.Stream); result = XmlUtil.Deserialize <pubblicazione>(ss); } return(result); }
/// <summary> /// Confermo la serie documentale AVCP e bandi di gara /// </summary> private void ConfirmDraftAvcpSeriesItem(Resolution resolution) { //Se sto confermando Bandi di Gara ed ho una serie AVCP associata if (HasAvcpSeriesToAutomaticConfirm(resolution)) { ICollection <DocumentSeriesItem> seriesToComplete = FacadeFactory.Instance.ResolutionFacade.GetSeriesToComplete(resolution); DocumentSeriesItem avcpSeriesItem = seriesToComplete.SingleOrDefault(s => s.DocumentSeries.Id == DocSuiteContext.Current.ProtocolEnv.AvcpDocumentSeriesId); //Imposto la data di pubblicazione quando l'atto sarà ritirato avcpSeriesItem.PublishingDate = resolution.PublishingDate.Value.AddDays(15); if (DocSuiteContext.Current.ResolutionEnv.CompleteTransparencyExecutiveStepEnabled && resolution.EffectivenessDate.HasValue) { avcpSeriesItem.PublishingDate = resolution.EffectivenessDate; } BiblosChainInfo avcpChain = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainChainInfo(avcpSeriesItem); FacadeFactory.Instance.DocumentSeriesItemFacade.UpdateDocumentSeriesItem(avcpSeriesItem, avcpChain, null, null, $"Pubblicata serie AVCP {avcpSeriesItem.Year:0000}/{avcpSeriesItem.Number:0000000} in data {avcpSeriesItem.PublishingDate:dd/MM/yyyy}"); bool hasInserted = avcpSeriesItem.Status == DocumentSeriesItemStatus.Active; FacadeFactory.Instance.DocumentSeriesItemFacade.AssignNumber(avcpSeriesItem); if (hasInserted) { FacadeFactory.Instance.DocumentSeriesItemFacade.SendUpdateDocumentSeriesItemCommand(avcpSeriesItem); } else { FacadeFactory.Instance.DocumentSeriesItemFacade.SendInsertDocumentSeriesItemCommand(avcpSeriesItem); } } }
private void FlushDocuments(DocumentSeriesItem item) { // Documento presente, lo sostituisco var toSave = FacadeFactory.Instance.DocumentSeriesItemFacade.GetAttributes(item); var newChain = new BiblosChainInfo(); newChain.AddAttributes(toSave); item.IdMain = newChain.ArchiveInBiblos(item.Location.ProtBiblosDSDB); }
public Guid CheckResolutionKindDocumentSeries(Resolution resl, DocumentSeriesItem documentSeriesItem) { ResolutionKind rk = _dao.GetById(resl.ResolutionKind.Id, false); if (rk.ResolutionKindDocumentSeries.Any() && rk.ResolutionKindDocumentSeries.Where(x => x.DocumentSeries.Id == documentSeriesItem.DocumentSeries.Id).Any()) { return(rk.ResolutionKindDocumentSeries.Where(x => x.DocumentSeries.Id == documentSeriesItem.DocumentSeries.Id).First().Id); } return(Guid.Empty); }
internal override IEvent CreateUpdateEvent(ICommandCQRSUpdate command, DocumentUnit documentUnit = null) { IEvent evt = null; try { DocumentSeriesItem documentSeriesItem = ((ICommandUpdateDocumentSeriesItem)command).ContentType.ContentTypeValue; evt = new EventUpdateDocumentSeriesItem(command.TenantName, command.TenantId, command.TenantAOOId, command.Identity, documentSeriesItem, ((ICommandCQRSFascicolable)command).CategoryFascicle, documentUnit); } catch (Exception ex) { _logger.WriteError(new LogMessage(string.Concat("DocumentSeriesItem, CreateUpdateEvent Error: ", command.GetType())), ex, LogCategories); throw ex; } return(evt); }
public DocumentSeriesItemRelations(DocumentSeriesItem FirstDocumentSeriesItem, DocumentSeriesItem SecondDocumentSeriesItem) { _firstItem = FirstDocumentSeriesItem; _secondItem = SecondDocumentSeriesItem; }
protected override void AfterSave(Fascicle entity) { try { _logger.WriteDebug(new LogMessage($"VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Fascicles.AfterSave with entity UniqueId {entity.UniqueId}"), LogCategories); if (CurrentDeleteActionType.HasValue && CurrentDeleteActionType == DeleteActionType.CancelFascicle) { IQueryable <FascicleDocumentUnit> documentUnits = _unitOfWork.Repository <FascicleDocumentUnit>().GetByFascicle(entity.UniqueId); ServiceBusMessage message; foreach (FascicleDocumentUnit item in documentUnits) { if (item.DocumentUnit.Environment == (int)DSWEnvironmentType.Protocol) { Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueId(item.DocumentUnit.UniqueId).Single(); message = GenerateMessage(item.DocumentUnit.Category, (int)DSWEnvironmentType.Protocol, (categoryFascicle) => new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, item.DocumentUnit.TenantAOO.UniqueId, null, null, null, new IdentityContext(_currentIdentity.FullUserName), protocol, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } if (item.DocumentUnit.Environment == (int)DSWEnvironmentType.Resolution) { Resolution resolution = _unitOfWork.Repository <Resolution>().GetByUniqueId(item.DocumentUnit.UniqueId).Single(); ResolutionModel resolutionModel = _mapper.Map(resolution, new ResolutionModel()); _mapper.FileResolution = _unitOfWork.Repository <FileResolution>().GetByResolution(item.DocumentUnit.EntityId).SingleOrDefault(); _mapper.ResolutionRoles = _unitOfWork.Repository <ResolutionRole>().GetByResolution(item.DocumentUnit.EntityId); message = GenerateMessage(item.DocumentUnit.Category, (int)DSWEnvironmentType.Resolution, (categoryFascicle) => new CommandUpdateResolution(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, item.DocumentUnit.TenantAOO.UniqueId, new IdentityContext(_currentIdentity.FullUserName), resolutionModel, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } if (item.DocumentUnit.Environment == (int)DSWEnvironmentType.DocumentSeries) { DocumentSeriesItem documentSeriesItem = _unitOfWork.Repository <DocumentSeriesItem>().GetFullByUniqueId(item.DocumentUnit.UniqueId).SingleOrDefault(); message = GenerateMessage(item.DocumentUnit.Category, (int)DSWEnvironmentType.DocumentSeries, (categoryFascicle) => new CommandUpdateDocumentSeriesItem(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, item.DocumentUnit.TenantAOO.UniqueId, null, new IdentityContext(_currentIdentity.FullUserName), documentSeriesItem, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } if (item.DocumentUnit.Environment >= 100) { UDSBuildModel commandModel = _mapperUnitOfwork.Repository <IDomainMapper <DocumentUnit, UDSBuildModel> >().Map(item.DocumentUnit, new UDSBuildModel()); commandModel.UniqueId = item.DocumentUnit.UniqueId; commandModel.RegistrationDate = item.DocumentUnit.RegistrationDate; commandModel.RegistrationUser = item.DocumentUnit.RegistrationUser; message = GenerateMessage(item.DocumentUnit.Category, item.DocumentUnit.Environment, (categoryFascicle) => new CommandCQRSUpdateUDSData(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, item.DocumentUnit.TenantAOO.UniqueId, new IdentityContext(_currentIdentity.FullUserName), commandModel, categoryFascicle, null, null, null, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } } } if (CurrentInsertActionType.HasValue || CurrentUpdateActionType.HasValue) { if (CurrentInsertActionType.HasValue) { Task.Run(async() => { FascicleFolder fascicleNode = new FascicleFolder { UniqueId = Guid.NewGuid(), Fascicle = entity, Name = "Fascicolo", Category = entity.Category, Status = FascicleFolderStatus.Active, Typology = FascicleFolderTypology.Fascicle }; _unitOfWork.Repository <FascicleFolder>().Insert(fascicleNode); await _unitOfWork.SaveChangesAsync(); _logger.WriteDebug(new LogMessage($"Created principal folder from Fascicle.UniqueId {entity.UniqueId}"), LogCategories); Fascicle fascicleTemplateModel = null; if (entity.FascicleTemplate != null && !string.IsNullOrEmpty(entity.FascicleTemplate.JsonModel)) { fascicleTemplateModel = JsonConvert.DeserializeObject <Fascicle>(entity.FascicleTemplate.JsonModel, Defaults.DefaultJsonSerializer); if (fascicleTemplateModel != null && fascicleTemplateModel.FascicleFolders.Any()) { _logger.WriteDebug(new LogMessage($"Evaluating fascicle template {entity.FascicleTemplate.UniqueId} with {fascicleTemplateModel.FascicleFolders.Count} folders from Fascicle.UniqueId {entity.UniqueId}"), LogCategories); IEnumerable <FascicleFolder> results = fascicleTemplateModel.FascicleFolders.Where(f => f.Typology == FascicleFolderTypology.SubFascicle); await RecursiveInsertFascicleFoldersAsync(entity, fascicleNode, results, results.Where(f => !f.ParentInsertId.HasValue)); } } }).Wait(); } IIdentityContext identity = new IdentityContext(_currentIdentity.FullUserName); Fascicle fascicle = _unitOfWork.Repository <Fascicle>().GetByUniqueId(entity.UniqueId); ICQRS command = new CommandCreateFascicle(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, identity, fascicle); if (CurrentUpdateActionType.HasValue) { command = new CommandUpdateFascicle(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, identity, fascicle); } foreach (IWorkflowAction workflowAction in WorkflowActions) { workflowAction.IdWorkflowActivity = IdWorkflowActivity; command.WorkflowActions.Add(workflowAction); } ServiceBusMessage message = _cqrsMapper.Map(command, new ServiceBusMessage()); if (message == null || string.IsNullOrEmpty(message.ChannelName)) { throw new DSWException($"Queue name to command [{command}] is not mapped", null, DSWExceptionCode.SC_Mapper); } Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } } catch (DSWException ex) { _logger.WriteError(ex, LogCategories); } base.AfterSave(entity); }
private bool InsertResolution(JsonResolutionModel jsonModel) { FileLogger.Info(this.Name, "Inizio inserimento Atto"); Guid mainChainId = Guid.Empty; Guid attachmentsChainId = Guid.Empty; Resolution resolution = new Resolution(); string typeDescription = string.Empty; string typeContainerDescription = string.Empty; resolution.Id = Facade.ParameterFacade.GetIdresolution(); resolution.Status.Id = (short)ResolutionStatusId.Attivo; resolution.Year = jsonModel.Anno; resolution.ProposeDate = jsonModel.DataAdozione.ToLocalTime().Date; resolution.ProposeUser = DocSuiteContext.Current.User.FullUserName; resolution.AdoptionDate = jsonModel.DataAdozione.ToLocalTime().Date; resolution.AdoptionUser = DocSuiteContext.Current.User.FullUserName; resolution.Number = jsonModel.Numero; resolution.PublishingDate = jsonModel.DataAdozione.ToLocalTime().Date; resolution.PublishingUser = DocSuiteContext.Current.User.FullUserName; resolution.EffectivenessDate = jsonModel.DataEsecutiva.ToLocalTime().Date; resolution.EffectivenessUser = DocSuiteContext.Current.User.FullUserName; resolution.InclusiveNumber = jsonModel.Segnatura; resolution.ResolutionObject = jsonModel.Oggetto; resolution.Type.Id = jsonModel.DelDet; string[] splitted = jsonModel.Segnatura.Split('/'); if (splitted.Length > 1 && splitted[1] != null) { resolution.ServiceNumber = (splitted.Length > 2 && splitted[2] != null) ? string.Concat(splitted[1], "/", splitted[2]) : splitted[1]; } else { HandleFailure("InsertResolution - La segnatura dell'atto indicata nel file Json non è valida"); return(false); } if (jsonModel.DelDet == 1) { typeDescription = "Delibera"; typeContainerDescription = "Delibere"; } else { if (jsonModel.DelDet == 0) { typeDescription = "Determina"; typeContainerDescription = "Determine"; } else { HandleFailure("InsertResolution - Errore in elaborazione: la tipologia di atto selezionata non esiste"); return(false); } } IList <Container> containers = Facade.ContainerFacade.GetContainerByName(string.Concat(typeContainerDescription, " ", jsonModel.Proponente)); IList <ResolutionKind> resolutionsKind = new ResolutionKindFacade(DocSuiteContext.Current.User.FullUserName).GetByName(jsonModel.TipologiaAtto); IList <Contact> contacts = GetProposerContacts(jsonModel.Proponente); IList <Role> roles = Facade.RoleFacade.GetByName(jsonModel.Proponente); Category category = Facade.CategoryFacade.GetById(Parameters.ImportResolutionCategoryId); if (containers != null && containers.Count() == 1) { resolution.Container = containers.First(); resolution.Location = resolution.Container.ReslLocation; } else { HandleFailure(string.Concat("InsertResolution - Errore in elaborazione del contenitore: il contenitore ", typeContainerDescription, " ", jsonModel.Proponente, " non esiste o non è univoco.")); return(false); } if (contacts != null && contacts.Count() == 1) { resolution.AddProposer(contacts.First()); } else { HandleFailure("InsertResolution - Errore in elaborazione del contatto selezionato: il contatto selezionato non esiste o non è univoco"); return(false); } if (category != null) { resolution.Category = category; } else { HandleFailure("InsertResolution - Errore in elaborazione del classificatore: classificatore non trovato."); return(false); } if (resolutionsKind != null && resolutionsKind.Any() && resolutionsKind.Count() == 1) { resolution.ResolutionKind = resolutionsKind.First(); } else { HandleFailure("InsertResolution - Errore in elaborazione della tipologia di atto: la tipologia di atto non esiste o non è univoca."); return(false); } resolution.WorkflowType = Facade.TabMasterFacade.GetFieldValue("WorkflowType", DocSuiteContext.Current.ResolutionEnv.Configuration, jsonModel.DelDet); string SignatureDocument = String.Concat(DocSuiteContext.Current.ResolutionEnv.CorporateAcronym, " ", typeDescription, " ", jsonModel.Segnatura, " del ", jsonModel.DataAdozione.ToLocalTime().ToString("d")); string SignatureAttachment = String.Concat(SignatureDocument, " (Allegato)"); try { FileLogger.Info(this.Name, "InsertResolution - Inizio caricamento documenti in Biblos."); string mainDocumentPath = string.Concat(Parameters.ImportResolutionSourceFolder, jsonModel.MaindocumentPath); FileDocumentInfo fileDocumentInfo = new FileDocumentInfo(new FileInfo(mainDocumentPath)); fileDocumentInfo.Signature = SignatureDocument; BiblosDocumentInfo storedDocumentInfo = fileDocumentInfo.ArchiveInBiblos(resolution.Location.DocumentServer, resolution.Location.ReslBiblosDSDB, Guid.Empty); mainChainId = storedDocumentInfo.ChainId; FileLogger.Info(this.Name, "InsertResolution - Documento principale salvato correttamente in Biblos."); int integerMainChainId = storedDocumentInfo.BiblosChainId; int integerAttachmentChainId = -1; FileDocumentInfo attachment; string attachmentDocumentPath; foreach (string attachmentRelativePath in jsonModel.AttachmentsDocumentPath) { attachmentDocumentPath = string.Concat(Parameters.ImportResolutionSourceFolder, attachmentRelativePath); attachment = new FileDocumentInfo(new FileInfo(attachmentDocumentPath)); attachment.Signature = SignatureAttachment; BiblosDocumentInfo attachmentDocumentInfo = attachment.ArchiveInBiblos(resolution.Location.DocumentServer, resolution.Location.ReslBiblosDSDB, attachmentsChainId); attachmentsChainId = attachmentDocumentInfo.ChainId; integerAttachmentChainId = attachmentDocumentInfo.BiblosChainId; FileLogger.Info(this.Name, "InsertResolution - Allegato salvato correttamente in Biblos."); } FileResolution fileResolution = new FileResolution(); fileResolution.Id = resolution.Id; fileResolution.IdResolutionFile = integerMainChainId; fileResolution.IdProposalFile = integerMainChainId; fileResolution.IdAssumedProposal = integerMainChainId; if (integerAttachmentChainId > 0) { fileResolution.IdAttachements = integerAttachmentChainId; } resolution.File = fileResolution; FileLogger.Info(this.Name, "InsertResolution - Fine caricamento documenti in Biblos."); } catch (Exception ex) { HandleFailure(string.Concat("InsertResolution - Errore in elaborazione del salvataggio dell'atto in Biblos: ", ex.Message)); return(false); } resolution.ResolutionWorkflows = new List <ResolutionWorkflow>(); resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 1, 0)); resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 2, 0)); resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 3, 0)); resolution.ResolutionWorkflows.Add(CreateResolutionWorkflow(resolution, 4, 1)); IEnumerable <ResolutionKindDocumentSeries> resolutionDocumentSeries = resolution.ResolutionKind.ResolutionKindDocumentSeries; IList <BiblosChainInfo> documents; DocumentSeriesItem documentSeriesItem; ResolutionDocumentSeriesItem resolutionDocumentSeriesItem; using (NHibernate.ITransaction transaction = NHibernateSession.BeginTransaction()) { try { FileLogger.Info(this.Name, "InsertResolution - Inizio transaction."); Facade.ResolutionFacade.SaveWithoutTransaction(ref resolution); FileLogger.Info(this.Name, "InsertResolution - Inserimento autorizzazioni atto."); if (contacts.First().Role != null) { Facade.ResolutionRoleFacade.AddRole(resolution, contacts.First().Role.Id, DocSuiteContext.Current.ResolutionEnv.AuthorizInsertType, false); } foreach (ResolutionKindDocumentSeries item in resolutionDocumentSeries) { documents = new List <BiblosChainInfo>(); documentSeriesItem = new DocumentSeriesItem(); resolutionDocumentSeriesItem = new ResolutionDocumentSeriesItem(); documentSeriesItem.Status = DocumentSeriesItemStatus.Draft; documentSeriesItem.DocumentSeries = Facade.DocumentSeriesFacade.GetById(item.DocumentSeries.Id); documentSeriesItem.Subject = resolution.ResolutionObject; documentSeriesItem.Category = resolution.Category; documentSeriesItem.IdMain = mainChainId; Facade.DocumentSeriesItemFacade.SaveDocumentSeriesItem(documentSeriesItem, resolution.Year.Value, new BiblosChainInfo(new List <DocumentInfo>()), null, null, DocSuiteContext.Current.User.FullUserName, DocumentSeriesItemStatus.Draft, string.Concat("Inserimento bozza di ", item.DocumentSeries.Name), false); if (roles != null && roles.Any() && roles.Count() == 1) { Facade.DocumentSeriesItemRoleFacade.AddOwnerRole(documentSeriesItem, roles.First(), false); } else { HandleFailure("InsertResolution - Errore in elaborazione della tipologia di atto: la tipologia di atto non esiste o non è univoca."); return(false); } resolutionDocumentSeriesItem.IdDocumentSeriesItem = documentSeriesItem.Id; resolutionDocumentSeriesItem.Resolution = resolution; Facade.ResolutionDocumentSeriesItemFacade.SaveWithoutTransaction(ref resolutionDocumentSeriesItem); } transaction.Commit(); //TODO:Invio comando di creazione Resolution alle WebApi // facadeFactory.ResolutionFacade.SendCreateResolutionCommand(resolution); FileLogger.Info(this.Name, "InsertResolution - Transaction completata con successo."); } catch (Exception ex) { FileLogger.Error(this.Name, String.Format("InsertResolution - Errore in salvataggio di atto: Message: {0} - StackTrace: {1}", ex.Message, ex.StackTrace)); transaction.Rollback(); } } Facade.ResolutionLogFacade.Log(resolution, ResolutionLogType.RI, string.Concat("Inserimento atto n.", resolution.InclusiveNumber)); return(true); }
protected override void AfterSave(FascicleDocumentUnit entity) { try { _logger.WriteDebug(new LogMessage(string.Concat("VecompSoftware.DocSuite.Private.WebAPI.Controllers.Entity.Fascicles.FascicleDocumentUnit.AfterSave with entity UniqueId ", entity.UniqueId)), LogCategories); ServiceBusMessage message = null; if (entity.ReferenceType == ReferenceType.Fascicle) { switch (entity.DocumentUnit.Environment) { case 1: { Collaboration collaboration = null; Guid? collaborationUniqueId = null; int? collaborationId = null; string collaborationTemplateName = string.Empty; Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueIdWithRole(entity.DocumentUnit.UniqueId).SingleOrDefault(); if (protocol != null) { collaboration = _unitOfWork.Repository <Collaboration>().GetByProtocol(protocol.Year, protocol.Number).SingleOrDefault(); if (collaboration != null) { collaborationId = collaboration.EntityId; collaborationUniqueId = collaboration.UniqueId; collaborationTemplateName = collaboration.TemplateName; } } message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Protocol, (categoryFascicle) => new CommandUpdateProtocol(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, protocol.TenantAOO.UniqueId, collaborationUniqueId, collaborationId, collaborationTemplateName, new IdentityContext(_currentIdentity.FullUserName), protocol, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); break; } case 2: { Resolution resolution = _unitOfWork.Repository <Resolution>().GetFullByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); if (resolution.AdoptionDate.HasValue) { ResolutionModel resolutionModel = _mapper.Map(resolution, new ResolutionModel()); _mapper.FileResolution = _unitOfWork.Repository <FileResolution>().GetByResolution(resolution.EntityId).SingleOrDefault(); _mapper.ResolutionRoles = _unitOfWork.Repository <ResolutionRole>().GetByResolution(resolution.EntityId); message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Resolution, (categoryFascicle) => new CommandUpdateResolution(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), resolutionModel, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } break; } case 4: { DocumentSeriesItem documentSeriesItem = _unitOfWork.Repository <DocumentSeriesItem>().GetFullByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.DocumentSeries, (categoryFascicle) => new CommandUpdateDocumentSeriesItem(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, null, new IdentityContext(_currentIdentity.FullUserName), documentSeriesItem, categoryFascicle, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); break; } default: { if (entity.DocumentUnit.Environment >= 100) { UDSBuildModel commandModel = _mapperUnitOfwork.Repository <IDomainMapper <DocumentUnit, UDSBuildModel> >().Map(entity.DocumentUnit, new UDSBuildModel()); commandModel.UniqueId = entity.DocumentUnit.UniqueId; commandModel.UDSId = entity.DocumentUnit.UniqueId; commandModel.RegistrationDate = entity.DocumentUnit.RegistrationDate; commandModel.RegistrationUser = entity.DocumentUnit.RegistrationUser; message = GenerateMessage(entity.DocumentUnit.Category, entity.DocumentUnit.Environment, (categoryFascicle) => new CommandCQRSUpdateUDSData(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, entity.DocumentUnit.TenantAOO?.UniqueId ?? Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), commandModel, categoryFascicle, entity.DocumentUnit, null, null, null)); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } break; } } } if (CurrentInsertActionType.HasValue) { message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Fascicle, (categoryFascicle) => { return(new CommandCreateFascicleDocumentUnit(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), entity)); }); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } if (CurrentDeleteActionType.HasValue) { message = GenerateMessage(entity.DocumentUnit.Category, (int)DSWEnvironmentType.Fascicle, (categoryFascicle) => { return(new CommandDeleteFascicleDocumentUnit(_parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId, Guid.Empty, new IdentityContext(_currentIdentity.FullUserName), entity)); }); Task.Run(async() => { await _queueService.SubscribeQueue(message.ChannelName).SendToQueueAsync(message); }).Wait(); } } catch (DSWException ex) { _logger.WriteError(ex, LogCategories); } base.AfterSave(entity); }
public bool ProcessFile(string fileName, ref int rowImported, ref int totalRow) { bool res = true; TaskInfo tInfo = TaskInfo.Load(fileName); TaskHeader task = FacadeFactory.Instance.TaskHeaderFacade.GetById(tInfo.taskId); DocSuiteWebAPI.DocumentSeriesItemDTO dto = Newtonsoft.Json.JsonConvert.DeserializeObject <DocSuiteWebAPI.DocumentSeriesItemDTO>(tInfo.taskCode); FileLogger.Info(this.LoggerName, String.Format("Elaborazione file '{0}'", fileName)); TaskDetail taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.Info, Title = String.Format("Elaborazione file '{0}'", fileName), TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); //informazioni sull'archivio DocumentSeries docSeries = FacadeFactory.Instance.DocumentSeriesFacade.GetById(dto.IdDocumentSeries.Value); IList <DocumentSeriesSubsection> docSeriesSubsections = FacadeFactory.Instance.DocumentSeriesSubsectionFacade.GetAll(); ArchiveInfo archInfo = GetSelectedArchiveInfo(docSeries); List <string> columns = new List <string>(_basicFields); columns.AddRange(archInfo.VisibleChainAttributes.Select(p => p.Name)); string excelVers = ""; if (Path.GetExtension(tInfo.documentFilename).ToLower() == ".xls") { excelVers = "Excel 8.0"; } if (Path.GetExtension(tInfo.documentFilename).ToLower() == ".xlsx") { excelVers = "Excel 12.0"; } rowImported = 0; List <List <string> > righeErrore = new List <List <string> >(); string connStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\";Extended Properties=\"{1};HDR=Yes;IMEX=1;\"", tInfo.documentFilename, excelVers); using (OleDbConnection conn = new OleDbConnection(connStr)) { conn.Open(); string sheetName = conn.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString(); //Gestione del file excel IDbCommand command = conn.CreateCommand(); command.CommandText = string.Format("SELECT {0} FROM [{1}]", string.Format("[{0}]", string.Join("], [", columns)), sheetName); command.CommandType = CommandType.Text; using (IDataReader dr = command.ExecuteReader()) { if (!dr.Read()) { dr.Close(); taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.ErrorType, Title = "Foglio excel vuoto.", TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); throw new DocSuiteException("Foglio excel vuoto."); } //Verifica delle colonne DataTable dt = dr.GetSchemaTable(); if (dt.Select("ColumnName = 'Subject'").Length < 1) { taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.ErrorType, Title = "Colonna [Subject] mancante.", TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); throw new DocSuiteException("Colonna [Subject] mancante."); } foreach (ArchiveAttribute attribute in archInfo.VisibleChainAttributes) { int columnIndex = dt.Select(string.Format("ColumnName = '{0}'", attribute.Name)).Length; if (columnIndex < 1 & attribute.Required) { taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.ErrorType, Title = string.Format("Colonna obbligatoria [{0}] mancante.", attribute.Name), TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); throw new DocSuiteException(string.Format("Colonna obbligatoria [{0}] mancante.", attribute.Name)); } } int currentRow = 0; //import while (true) { string rowId = string.Empty; string message = string.Empty; string subSection = string.Empty; try { rowId = dr["Subject"].ToString(); if (tInfo.IsRowProcessed(rowId)) { message = string.Format("Riga [{0}]: saltata poiché è già stato processato un elemento con campo oggetto '{1}'", currentRow + 2, rowId); FileLogger.Info(LoggerName, message); taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.Info, Title = message, TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); //next if (!dr.Read()) { break; } continue; } // Catena Biblos per la gestione dei Metadati BiblosChainInfo chain = new BiblosChainInfo(); List <DocumentInfo> mainDocs = new List <DocumentInfo>(); if (dt.Select("ColumnName = 'DOC_Main'").Length == 1) { mainDocs = ParseDocumentString(dr["DOC_Main"].ToString()); chain.AddDocuments(mainDocs); } // Recupero i metadati da EXCEL e li salvo nella catena foreach (ArchiveAttribute attribute in archInfo.VisibleChainAttributes) { if (dt.Select(string.Format("ColumnName = '{0}'", attribute.Name)).Length < 1) { continue; } FileLogger.Debug(LoggerName, attribute.Name); chain.AddAttribute(attribute.Name, string.Format(attribute.Format, dr[attribute.Name])); } // DocumentSeriesItem da salvare DocumentSeriesItem item = new DocumentSeriesItem(); if (dt.Select("ColumnName = 'Subsection'").Length > 0) { subSection = dr["Subsection"].ToString(); if (!subSection.IsNullOrEmpty()) { DocumentSeriesSubsection subSectionToAdd = docSeriesSubsections.FirstOrDefault(x => x.Description == subSection); if (subSectionToAdd != null) { item.DocumentSeriesSubsection = subSectionToAdd; } else { message = string.Format("Sottosezione [{0}] della serie documentale [{1}] non caricata perchè non presente sul database", subSection, docSeries.Name); FileLogger.Info(LoggerName, message); } } } item.DocumentSeries = docSeries; item.Subject = dr["Subject"].ToString(); // Recupero e salvo i dati di classificazione Category selectedCategory = FacadeFactory.Instance.CategoryFacade.GetById(dto.Category.Id.Value); Category root = selectedCategory.Root; if (selectedCategory.Equals(root)) { item.Category = selectedCategory; } else { item.Category = root; item.SubCategory = selectedCategory; } // Recupero e salvo l'evenatuale data di pubblicazione if (dto.PublishingDate.HasValue) { item.PublishingDate = dto.PublishingDate.Value; } // Imposto la STATUS desiderato DocumentSeriesItemStatus status = (DocumentSeriesItemStatus)dto.Status; List <DocumentInfo> annexed = new List <DocumentInfo>(); if (dt.Select("ColumnName = 'DOC_Annexed'").Length == 1) { annexed.AddRange(ParseDocumentString(dr["DOC_Annexed"].ToString())); } List <DocumentInfo> unpublished = new List <DocumentInfo>(); if (dt.Select("ColumnName = 'DOC_UnpublishedAnnexed'").Length == 1) { unpublished.AddRange(ParseDocumentString(dr["DOC_UnpublishedAnnexed"].ToString())); } // Salvo l'Item in DB FacadeFactory.Instance.DocumentSeriesItemFacade.SaveDocumentSeriesItem(item, chain, annexed, unpublished, status, "Registrazione importata da documento EXCEL."); //A questo punto sono certo che la procedura ha salvato in BiblosDS i documenti, //li rimuovo dalla sorgente. RemoveProcessedFiles(mainDocs, annexed, unpublished); message = string.Format("Riga [{0}]: Ok", currentRow + 2); FileLogger.Info(LoggerName, message); taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.Info, Title = message, TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); tInfo.AddRowInfo(rowId, message, RowInfo.RowStatus.Processed); // Incremento il counter rowImported += 1; } catch (Exception ex) { int count = dr.FieldCount; //genero la lista da inserire nella lista di errori List <string> errorValues = new List <string>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { errorValues.Add(dr.GetValue(i).ToString()); } righeErrore.Add(errorValues); FileLogger.Debug(LoggerName, "QRY su EXEL: " + command.CommandText); message = string.Format("Riga [{0}]: Errore - {1}", currentRow + 2, ex.Message); FileLogger.Error(LoggerName, message, ex); taskDetail = new TaskDetail() { DetailType = DetailTypeEnum.ErrorType, Title = message, ErrorDescription = ex.StackTrace, TaskHeader = task }; FacadeFactory.Instance.TaskDetailFacade.Save(ref taskDetail); tInfo.AddRowInfo(rowId, message, RowInfo.RowStatus.Error); res = false; } finally { currentRow += 1; } //next if (!dr.Read()) { break; } } totalRow = currentRow; } // chiudo la conn oledb conn.Close(); } return(res); }
/// <summary> /// Metodo per il salvataggio di un DataSet in Serie AVCP /// </summary> /// <param name="pub">Oggetto da salvare</param> /// <param name="item">DocumentSeriesItem in cui deve essere salvato</param> /// <param name="username">Nome dell'operatore che esegue il savataggio</param> /// <returns>Restituisce l'oggetto contenente tutte le informazioni sull'importazione eseguita</returns> public SetDataSetResult SetDataSetPub(pubblicazione pub, DocumentSeriesItem item, string username, bool saveAlways) { if (pub == null) { throw new ArgumentNullException("pub", "Oggetto [pubblicazione] nullo"); } // Creo l'oggetto di ritorno var tor = new SetDataSetResult(); tor.Item = item; try { // Recupero il documento principale tor.Chain = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainChainInfo(tor.Item); } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di recupero documento catena principale.", ex); } try { // Verifico data ultimo aggiornamento tor.Step = 100; if (!saveAlways && !tor.Chain.Documents.IsNullOrEmpty() && tor.Chain.Attributes.ContainsKey(AttributeDataUltimoAggiornamento)) { DateTime lastUpdate = DateTime.MinValue; if (!DateTime.TryParse(tor.Chain.Attributes[AttributeDataUltimoAggiornamento], out lastUpdate)) { tor.Chain.AddAttribute(AttributeDataUltimoAggiornamento, pub.metadata.dataUltimoAggiornamentoDataset.ToString("s")); } tor.LastUpdate = lastUpdate; FileLogger.Debug(LoggerName, string.Format("tor.LastUpdate = {0}", tor.LastUpdate.Date)); FileLogger.Debug(LoggerName, string.Format("pub.metadata.dataUltimoAggiornamentoDataset.Date = {0}", pub.metadata.dataUltimoAggiornamentoDataset.Date)); // Aggiorno solo se la data in arrivo è maggiore di quella salvata if (pub.metadata.dataUltimoAggiornamentoDataset.Date <= tor.LastUpdate.Date) { tor.Updated = false; return(tor); } } tor.Updated = true; } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di verifica data ultimo aggiornamento.", ex); } try { // Aggiornamento necessario, eseguo eventaule Flush del documento tor.Step = 200; if (!tor.Chain.Documents.IsNullOrEmpty()) { FlushDocuments(tor.Item); tor.Flushed = true; // Ricarico la nuova catena creata tor.Chain = FacadeFactory.Instance.DocumentSeriesItemFacade.GetMainChainInfo(tor.Item); } } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di Flush del documento.", ex); } try { // Salvo il documento nella catena tor.Step = 300; tor.SerializedDataSet = AVCPHelper.Serialize(pub); var doc = new MemoryDocumentInfo(tor.SerializedDataSet.ToBytes(), "dataset.xml", ""); tor.Chain.AddDocument(doc); } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di salvataggio del documento in catena.", ex); } try { // Riporto i Metadati in Serie Documentale tor.Step = 400; tor.Chain.AddAttribute(AttributeUrlFile, string.Format(DocSuiteContext.Current.ProtocolEnv.AVCPDatasetUrlMask, tor.Item.Id)); if (pub.metadata.dataUltimoAggiornamentoDataset != DateTime.MinValue) { tor.Chain.AddAttribute(AttributeDataUltimoAggiornamento, pub.metadata.dataUltimoAggiornamentoDataset.ToString("s")); } if (pub.metadata.licenza != null) { tor.Chain.AddAttribute(AttributeLicenza, pub.metadata.licenza.ToString()); } tor.Chain.AddAttribute(AttributeAbstract, pub.metadata.@abstract); tor.Chain.AddAttribute(AttributeAnnoRiferimento, pub.metadata.annoRiferimento.ToString()); tor.Chain.AddAttribute(AttributeTitolo, pub.metadata.titolo); if (pub.metadata.dataPubblicazioneDataset != DateTime.MinValue) { tor.Chain.AddAttribute(AttributeDataPubblicazione, pub.metadata.dataPubblicazioneDataset.ToString("s")); } tor.Chain.AddAttribute(AttributeEntePubblicatore, pub.metadata.entePubblicatore); } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di impostazione attributi in catena.", ex); } try { // Eseguo il salvataggio dell'Item tor.Step = 500; FacadeFactory.Instance.DocumentSeriesItemFacade.UpdateDocumentSeriesItem(tor.Item, tor.Chain, username, $"Modificata registrazione AVCP {tor.Item.Year:0000}/{tor.Item.Number:0000000}"); // Invio comando di update alle WebApi if (tor.Item.Status == DocumentSeriesItemStatus.Active) { FacadeFactory.Instance.DocumentSeriesItemFacade.SendUpdateDocumentSeriesItemCommand(tor.Item); } tor.Saved = true; } catch (Exception ex) { throw new SetDataSetResultException(tor, "Errore in fase di salvataggio finale.", ex); } return(tor); }
/// <summary> /// Aggiorna gli attributi della serie documentale per bandi di gara e contratti /// </summary> /// <param name="item"></param> /// <param name="pub"></param> /// <param name="archiveInfo"></param> /// <param name="chain"></param> /// <returns></returns> public BiblosChainInfo UpdateAttributeBandiDiGara(DocumentSeriesItem item, pubblicazione pub, ArchiveInfo archiveInfo, BiblosChainInfo chain) { foreach (ArchiveAttribute attribute in archiveInfo.Attributes) { string valueString = string.Empty; DynamicAttribute attr; try { attr = EnumHelper.ParseDescriptionToEnum <DynamicAttribute>(attribute.Name); } catch (Exception) { continue; } switch (attr) { case DynamicAttribute.Aggiudicatario: valueString = this.GetAziendeAggiudicatarie(pub); break; case DynamicAttribute.Lotti: valueString = this.GetLotti(pub); break; case DynamicAttribute.Liquidato: valueString = this.GetImportoSommeLiquidate(pub).ToString(); break; case DynamicAttribute.DitteInvitate: valueString = this.GetAziendeInvitate(pub); break; case DynamicAttribute.DittePartecipanti: valueString = this.GetAziendePartecipanti(pub); break; case DynamicAttribute.ProceduraAggiudicazione: valueString = this.GetSceltaContraente(pub); break; case DynamicAttribute.ImportoComplessivo: valueString = this.GetImportoAggiudicazione(pub).ToString(); break; case DynamicAttribute.StrutturaProponente: valueString = this.GetStrutturaProponente(pub); break; } if (!string.IsNullOrEmpty(valueString)) { chain.AddAttribute(attribute.Name, valueString); continue; } DateTime valueDatetime = DateTime.MinValue; switch (EnumHelper.ParseDescriptionToEnum <DynamicAttribute>(attribute.Name)) { case DynamicAttribute.DurataAl: DateTime?endDate = this.GetDataFineLavori(pub); if ((endDate.HasValue)) { valueDatetime = endDate.Value; } break; case DynamicAttribute.DurataDal: DateTime?startDate = this.GetDataInizioLavori(pub); if ((startDate.HasValue)) { valueDatetime = startDate.Value; } break; } if (valueDatetime != DateTime.MinValue) { chain.AddAttribute(attribute.Name, valueDatetime.ToString()); } } return(chain); }
internal override async Task <DocumentUnit> MappingInsertAsync(IContentBase entity, IIdentityContext identity) { DocumentUnit documentUnit = new DocumentUnit(); try { DocumentSeriesItem documentSeriesItem = (DocumentSeriesItem)entity; #region [ Base ] documentUnit.EntityId = documentSeriesItem.EntityId; documentUnit.Environment = (int)DocSuiteWeb.Entity.Commons.DSWEnvironmentType.DocumentSeries; documentUnit.LastChangedDate = null; documentUnit.LastChangedUser = null; documentUnit.Number = documentSeriesItem.Number.Value; documentUnit.RegistrationDate = documentSeriesItem.RegistrationDate; documentUnit.RegistrationUser = documentSeriesItem.RegistrationUser; documentUnit.Subject = documentSeriesItem.Subject; documentUnit.Title = string.Concat(documentSeriesItem.Year.Value, "/", documentSeriesItem.Number.Value.ToString("0000000")); documentUnit.UniqueId = documentSeriesItem.UniqueId; documentUnit.Year = (short)(documentSeriesItem.Year.Value); documentUnit.DocumentUnitName = documentSeriesItem.DocumentSeries.Name; documentUnit.Status = documentSeriesItem.Status == DocumentSeriesItemStatus.Active ? DocumentUnitStatus.Active : DocumentUnitStatus.Inactive; #endregion #region [ Navigation Properties ] documentUnit.UDSRepository = null; documentUnit.Category = documentSeriesItem.Category; documentUnit.Container = documentSeriesItem.DocumentSeries.Container; documentUnit.Fascicle = await _webApiClient.GetFascicleAsync(documentSeriesItem.UniqueId); foreach (DocumentSeriesItemRole item in documentSeriesItem.DocumentSeriesItemRoles) { documentUnit.DocumentUnitRoles.Add(new DocumentUnitRole() { UniqueIdRole = item.Role.UniqueId, RegistrationDate = DateTimeOffset.UtcNow, RegistrationUser = identity.User, AuthorizationRoleType = GetRoleType(string.Empty) }); } if (documentSeriesItem.IdAnnexed.HasValue && documentSeriesItem.IdAnnexed.Value != Guid.Empty) { AddDocumentUnitChain(documentUnit, documentSeriesItem.IdAnnexed.Value, ChainType.AnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } if (documentSeriesItem.IdUnpublishedAnnexed.HasValue && documentSeriesItem.IdUnpublishedAnnexed.Value != Guid.Empty) { AddDocumentUnitChain(documentUnit, documentSeriesItem.IdUnpublishedAnnexed.Value, ChainType.UnpublishedAnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesUnpublishedAnnexedLocation.ProtocolArchive); } if (documentSeriesItem.IdMain.HasValue && documentSeriesItem.IdMain.Value != Guid.Empty) { BiblosDS.BiblosDS.Document document = _biblosClient.Document.GetDocumentChildren(documentSeriesItem.IdMain.Value).FirstOrDefault(); AddDocumentUnitChain(documentUnit, documentSeriesItem.IdMain.Value, ChainType.MainChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesLocation.ProtocolArchive, document != null ? document.Name : null); } if (documentSeriesItem.DematerialisationChainId.HasValue && documentSeriesItem.DematerialisationChainId.Value != Guid.Empty) { AddDocumentUnitChain(documentUnit, documentSeriesItem.DematerialisationChainId.Value, ChainType.DematerialisationChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } #endregion } catch (Exception ex) { _logger.WriteError(new LogMessage("DocumentSeriesItem, MappingInsertAsync Error: "), ex, LogCategories); throw ex; } return(documentUnit); }
internal override async Task <DocumentUnit> MappingUpdateAsync(IContentBase entity, DocumentUnit documentUnit, IIdentityContext identity) { try { DocumentSeriesItem documentSeriesItem = (DocumentSeriesItem)entity; #region [ Base ] documentUnit.LastChangedDate = documentSeriesItem.LastChangedDate; documentUnit.LastChangedUser = documentSeriesItem.LastChangedUser; documentUnit.Subject = documentSeriesItem.Subject; documentUnit.Title = documentUnit.Title; documentUnit.Status = documentSeriesItem.Status == DocumentSeriesItemStatus.Active ? DocumentUnitStatus.Active : DocumentUnitStatus.Inactive; #endregion #region [ Navigation Properties ] if (documentUnit.Category.UniqueId != documentSeriesItem.Category.UniqueId) { documentUnit.Category = documentSeriesItem.Category; } if (documentUnit.Container.UniqueId != documentSeriesItem.DocumentSeries.Container.UniqueId) { documentUnit.Container = documentSeriesItem.DocumentSeries.Container; } documentUnit.Fascicle = await _webApiClient.GetFascicleAsync(documentSeriesItem.UniqueId); if (documentSeriesItem.DocumentSeriesItemRoles == null || !documentSeriesItem.DocumentSeriesItemRoles.Any()) { documentSeriesItem.DocumentSeriesItemRoles.Clear(); } if (documentSeriesItem.DocumentSeriesItemRoles != null) { foreach (DocumentSeriesItemRole item in documentSeriesItem.DocumentSeriesItemRoles.Where(t => !documentUnit.DocumentUnitRoles.Any(x => x.UniqueIdRole == t.Role.UniqueId)).ToList()) { documentUnit.DocumentUnitRoles.Add(new DocumentUnitRole() { UniqueIdRole = item.Role.UniqueId, RegistrationDate = DateTimeOffset.UtcNow, RegistrationUser = identity.User, AuthorizationRoleType = GetRoleType(string.Empty) }); } foreach (DocumentUnitRole item in documentUnit.DocumentUnitRoles.Where(t => !documentSeriesItem.DocumentSeriesItemRoles.Any(x => x.Role.UniqueId == t.UniqueIdRole)).ToList()) { documentUnit.DocumentUnitRoles.Remove(item); } } if (documentSeriesItem.IdAnnexed.HasValue && documentSeriesItem.IdAnnexed.Value != Guid.Empty) { DocumentUnitChain annexed = documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.AnnexedChain).FirstOrDefault(); if (annexed != null) { if (annexed.IdArchiveChain != documentSeriesItem.IdAnnexed.Value) { documentUnit.DocumentUnitChains.Remove(annexed); AddDocumentUnitChain(documentUnit, documentSeriesItem.IdAnnexed.Value, ChainType.AnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } } else { AddDocumentUnitChain(documentUnit, documentSeriesItem.IdAnnexed.Value, ChainType.AnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } } else { foreach (DocumentUnitChain chain in documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.AnnexedChain).ToList()) { documentUnit.DocumentUnitChains.Remove(chain); } } if (documentSeriesItem.IdUnpublishedAnnexed.HasValue && documentSeriesItem.IdUnpublishedAnnexed.Value != Guid.Empty) { DocumentUnitChain unpublishedAnnexed = documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.UnpublishedAnnexedChain).FirstOrDefault(); if (unpublishedAnnexed != null) { if (unpublishedAnnexed.IdArchiveChain != documentSeriesItem.IdUnpublishedAnnexed.Value) { documentUnit.DocumentUnitChains.Remove(unpublishedAnnexed); AddDocumentUnitChain(documentUnit, documentSeriesItem.IdUnpublishedAnnexed.Value, ChainType.UnpublishedAnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesUnpublishedAnnexedLocation.ProtocolArchive); } } else { AddDocumentUnitChain(documentUnit, documentSeriesItem.IdUnpublishedAnnexed.Value, ChainType.UnpublishedAnnexedChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesUnpublishedAnnexedLocation.ProtocolArchive); } } else { foreach (DocumentUnitChain chain in documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.UnpublishedAnnexedChain).ToList()) { documentUnit.DocumentUnitChains.Remove(chain); } } if (documentSeriesItem.IdMain.HasValue && documentSeriesItem.IdMain.Value != Guid.Empty) { DocumentUnitChain main = documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.MainChain).FirstOrDefault(); if (main != null) { if (main.IdArchiveChain != documentSeriesItem.IdMain.Value) { documentUnit.DocumentUnitChains.Remove(main); BiblosDS.BiblosDS.Document document = _biblosClient.Document.GetDocumentChildren(documentSeriesItem.IdMain.Value).FirstOrDefault(); AddDocumentUnitChain(documentUnit, documentSeriesItem.IdMain.Value, ChainType.MainChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesLocation.ProtocolArchive, document != null ? document.Name : null); } } else { BiblosDS.BiblosDS.Document document = _biblosClient.Document.GetDocumentChildren(documentSeriesItem.IdMain.Value).FirstOrDefault(); AddDocumentUnitChain(documentUnit, documentSeriesItem.IdMain.Value, ChainType.MainChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesLocation.ProtocolArchive, document != null ? document.Name : null); } } else { foreach (DocumentUnitChain chain in documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.MainChain).ToList()) { documentUnit.DocumentUnitChains.Remove(chain); } } if (documentSeriesItem.DematerialisationChainId.HasValue && documentSeriesItem.DematerialisationChainId.Value != Guid.Empty) { DocumentUnitChain dematerialisation = documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.DematerialisationChain).FirstOrDefault(); if (dematerialisation != null) { if (dematerialisation.IdArchiveChain != documentSeriesItem.DematerialisationChainId.Value) { documentUnit.DocumentUnitChains.Remove(dematerialisation); AddDocumentUnitChain(documentUnit, documentSeriesItem.DematerialisationChainId.Value, ChainType.DematerialisationChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } } else { AddDocumentUnitChain(documentUnit, documentSeriesItem.DematerialisationChainId.Value, ChainType.DematerialisationChain, identity, documentSeriesItem.DocumentSeries.Container.DocumentSeriesAnnexedLocation.ProtocolArchive); } } else { foreach (DocumentUnitChain chain in documentUnit.DocumentUnitChains.Where(t => t.ChainType == ChainType.DematerialisationChain).ToList()) { documentUnit.DocumentUnitChains.Remove(chain); } } #endregion } catch (Exception ex) { _logger.WriteError(new LogMessage("DocumentSeriesItem, MappingUpdateAsync Error: "), ex, LogCategories); throw ex; } return(documentUnit); }
protected void PrepareDocumentUnitLog(FascicleDocumentUnit entity, FascicleLog fascicleLog) { if (entity.DocumentUnit.Environment == (int)DSWEnvironmentType.Protocol) { Protocol protocol = _unitOfWork.Repository <Protocol>().GetByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); ProtocolLog protocolLog = new ProtocolLog() { Year = entity.DocumentUnit.Year, Number = entity.DocumentUnit.Number, LogDate = fascicleLog.RegistrationDate.DateTime, LogType = "FS", Program = "Private.WebAPI", LogDescription = fascicleLog.LogDescription, RegistrationUser = fascicleLog.RegistrationUser, SystemComputer = fascicleLog.SystemComputer, Entity = protocol, }; protocolLog.Hash = HashGenerator.GenerateHash(string.Concat(protocolLog.RegistrationUser, "|", protocolLog.Year, "|", protocolLog.Number, "|", protocolLog.LogType, "|", protocolLog.LogDescription, "|", protocolLog.UniqueId, "|", protocolLog.Entity.UniqueId, "|", protocolLog.LogDate.ToString("yyyyMMddHHmmss"))); _unitOfWork.Repository <ProtocolLog>().Insert(protocolLog); } if (entity.DocumentUnit.Environment == (int)DSWEnvironmentType.Resolution) { Resolution resolution = _unitOfWork.Repository <Resolution>().GetByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); ResolutionLog resolutionLog = new ResolutionLog() { LogDate = fascicleLog.RegistrationDate.DateTime, LogType = "FS", Program = "Private.WebAPI", LogDescription = fascicleLog.LogDescription, RegistrationUser = fascicleLog.RegistrationUser, SystemComputer = fascicleLog.SystemComputer, Entity = resolution, }; resolutionLog.Hash = HashGenerator.GenerateHash(string.Concat(resolutionLog.RegistrationUser, "|", resolutionLog.LogType, "|", resolutionLog.LogDescription, "|", resolutionLog.UniqueId, "|", resolutionLog.Entity.UniqueId, "|", resolutionLog.LogDate.ToString("yyyyMMddHHmmss"))); _unitOfWork.Repository <ResolutionLog>().Insert(resolutionLog); } if (entity.DocumentUnit.Environment == (int)DSWEnvironmentType.DocumentSeries) { DocumentSeriesItem documentSeriesItem = _unitOfWork.Repository <DocumentSeriesItem>().GetByUniqueId(entity.DocumentUnit.UniqueId).SingleOrDefault(); DocumentSeriesItemLog documentSeriesItemLog = new DocumentSeriesItemLog() { LogDate = fascicleLog.RegistrationDate.DateTime, LogType = "FS", Program = "Private.WebAPI", LogDescription = fascicleLog.LogDescription, RegistrationUser = fascicleLog.RegistrationUser, SystemComputer = fascicleLog.SystemComputer, Entity = documentSeriesItem, }; documentSeriesItemLog.Hash = HashGenerator.GenerateHash(string.Concat(documentSeriesItemLog.RegistrationUser, "|", documentSeriesItemLog.LogType, "|", documentSeriesItemLog.LogDescription, "|", documentSeriesItemLog.UniqueId, "|", documentSeriesItemLog.Entity.UniqueId, "|", documentSeriesItemLog.LogDate.ToString("yyyyMMddHHmmss"))); _unitOfWork.Repository <DocumentSeriesItemLog>().Insert(documentSeriesItemLog); } if (entity.DocumentUnit.Environment >= 100) { UDSRepository uDSRepository = _unitOfWork.Repository <UDSRepository>().GetByIdDocumentUnit(entity.DocumentUnit.UniqueId); UDSLog log = new UDSLog() { LogType = UDSLogType.Delete, LogDescription = fascicleLog.LogDescription, SystemComputer = string.IsNullOrEmpty(fascicleLog.SystemComputer) ? Environment.MachineName : fascicleLog.SystemComputer, Entity = uDSRepository, RegistrationDate = fascicleLog.RegistrationDate.DateTime, RegistrationUser = fascicleLog.RegistrationUser, IdUDS = entity.DocumentUnit.UniqueId, Environment = entity.DocumentUnit.Environment, }; log.Hash = HashGenerator.GenerateHash(string.Concat(log.RegistrationUser, "|", log.LogType, "|", log.LogDescription, "|", log.UniqueId, "|", log.IdUDS, "|", log.RegistrationDate.ToString("yyyyMMddHHmmss"))); _unitOfWork.Repository <UDSLog>().Insert(log); } }