public static Guid?GetDocumentIdArchiveChainById(this IRepository <TemplateDocumentRepository> repository, Guid idTemplate)
        {
            TemplateDocumentRepository query = repository.Query(x => x.UniqueId == idTemplate, optimization: true)
                                               .SelectAsQueryable()
                                               .FirstOrDefault();

            return(query?.IdArchiveChain);
        }
        public ProtocolInitializer GetProtocolInitializer(IReadOnlyCollection <TenantModel> tenantModels, ProtocolModel protocolModel,
                                                          Collaboration collaboration, WorkflowProperty dsw_p_CollaborationSignSummaryTemplateId, WorkflowProperty dsw_a_Collaboration_GenerateSignSummary,
                                                          WorkflowProperty dsw_p_ProposerRole, UDSDto udsDto)
        {
            ProtocolInitializer protInitializer = new ProtocolInitializer();

            // Oggetto
            protInitializer.Subject = protocolModel.Object;
            // Protocol Type
            protInitializer.ProtocolType = protocolModel.ProtocolType.EntityShortId;
            //Note
            protInitializer.Notes = protocolModel.Note;
            //Protocollo
            protInitializer.DocumentProtocol = protocolModel.DocumentProtocol;
            //Date
            protInitializer.DocumentDate = protocolModel.DocumentDate;
            // Classificazione
            if (protocolModel.Category != null && protocolModel.Category.IdCategory.HasValue)
            {
                protInitializer.Category = FacadeFactory.Instance.CategoryFacade.GetById(protocolModel.Category.IdCategory.Value);
            }
            if (protocolModel.Container != null && protocolModel.Container.IdContainer.HasValue)
            {
                protInitializer.Containers = new List <Data.Container> {
                    FacadeFactory.Instance.ContainerFacade.GetById(Convert.ToInt32(protocolModel.Container.IdContainer))
                };
            }
            if (protocolModel.DocumentTypeCode != null)
            {
                protInitializer.DocumentTypeLabel = FacadeFactory.Instance.TableDocTypeFacade.GetByCode(protocolModel.DocumentTypeCode).Description;
            }

            string owner = DocSuiteContext.Current.User.UserName;

            // Gestione documenti
            if (protocolModel.MainDocument != null && !string.IsNullOrEmpty(protocolModel.MainDocument.FileName) &&
                (protocolModel.MainDocument.ContentStream != null || protocolModel.MainDocument.DocumentId.HasValue))
            {
                protInitializer.MainDocument = SaveStream(owner, protocolModel.MainDocument);
            }

            // Allegati
            IEnumerable <DocumentModel> results = null;

            if (protocolModel.Attachments != null && (results = protocolModel.Attachments.Where(f => !string.IsNullOrEmpty(f.FileName) && (f.ContentStream != null || f.DocumentId.HasValue))).Any())
            {
                protInitializer.Attachments = SaveStream(owner, results);
            }

            if (collaboration != null && dsw_p_CollaborationSignSummaryTemplateId != null && dsw_a_Collaboration_GenerateSignSummary != null &&
                dsw_a_Collaboration_GenerateSignSummary.ValueBoolean.HasValue && dsw_a_Collaboration_GenerateSignSummary.ValueBoolean.Value &&
                dsw_p_CollaborationSignSummaryTemplateId.ValueGuid.HasValue && dsw_p_CollaborationSignSummaryTemplateId.ValueGuid.Value != Guid.Empty)
            {
                TemplateDocumentRepository templateDocumentRepository = WebAPIImpersonatorFacade.ImpersonateFinder(new TemplateDocumentRepositoryFinder(tenantModels),
                                                                                                                   (impersonationType, finder) =>
                {
                    finder.UniqueId     = dsw_p_CollaborationSignSummaryTemplateId.ValueGuid.Value;
                    finder.EnablePaging = false;
                    return(finder.DoSearch().SingleOrDefault()?.Entity);
                });

                if (templateDocumentRepository != null)
                {
                    BiblosChainInfo        biblosChainInfo    = new BiblosChainInfo(templateDocumentRepository.IdArchiveChain);
                    DocumentInfo           biblosDocumentInfo = biblosChainInfo.Documents.Single(f => !f.IsRemoved);
                    List <BuildValueModel> buildValueModels   = new List <BuildValueModel>();
                    buildValueModels.Add(new BuildValueModel()
                    {
                        IsHTML = false,
                        Name   = "oggetto",
                        Value  = protInitializer.Subject,
                    });
                    DateTime signDate;
                    string   token;
                    foreach (CollaborationSign item in collaboration.CollaborationSigns)
                    {
                        signDate = item.SignDate ?? item.LastChangedDate.Value.DateTime;
                        token    = signDate.DayOfWeek == DayOfWeek.Sunday ? "la" : "il";
                        buildValueModels.Add(new BuildValueModel()
                        {
                            IsHTML = false,
                            Name   = $"signer_info_{item.Incremental}",
                            Value  = $"{item.SignName} {token} {signDate.ToLongDateString()}",
                        });
                    }
                    buildValueModels = BuildValueProposerRole(dsw_p_ProposerRole, buildValueModels);
                    buildValueModels = BuildValueUDS(udsDto, buildValueModels);
                    byte[] pdf = Services.StampaConforme.Service.BuildPDF(biblosDocumentInfo.Stream, buildValueModels.ToArray(), string.Empty);
                    if (protInitializer.Attachments == null)
                    {
                        protInitializer.Attachments = new List <DocumentInfo>();
                    }
                    protInitializer.Attachments.Add(SaveStream(owner, pdf, "riepilogo_firmatari.pdf"));
                }
            }
            // Annessi
            results = null;
            if (protocolModel.Annexes != null && (results = protocolModel.Annexes.Where(f => !string.IsNullOrEmpty(f.FileName) && (f.ContentStream != null || f.DocumentId.HasValue))).Any())
            {
                protInitializer.Annexed = SaveStream(owner, results);
            }

            // Contatti
            protInitializer.Senders    = new List <Data.ContactDTO>();
            protInitializer.Recipients = new List <Data.ContactDTO>();
            if (protocolModel.ContactManuals != null && protocolModel.ContactManuals.Any())
            {
                foreach (ProtocolContactManualModel protocolContactManualModel in protocolModel.ContactManuals)
                {
                    Data.Contact contact = new Data.Contact();
                    contact.ContactType   = new Data.ContactType(Data.ContactType.Aoo);
                    contact.Description   = protocolContactManualModel.Description;
                    contact.CertifiedMail = protocolContactManualModel.CertifiedEmail;
                    contact.EmailAddress  = protocolContactManualModel.EMail;
                    if (!string.IsNullOrEmpty(protocolContactManualModel.Address))
                    {
                        contact.Address         = new Data.Address();
                        contact.Address.Address = protocolContactManualModel.Address;
                    }

                    if (protocolContactManualModel.ComunicationType == ComunicationType.Sender)
                    {
                        protInitializer.Senders.Add(new Data.ContactDTO(contact, Data.ContactDTO.ContactType.Manual));
                    }
                    else
                    {
                        protInitializer.Recipients.Add(new Data.ContactDTO(contact, Data.ContactDTO.ContactType.Manual));
                    }
                }
            }
            if (protocolModel.Contacts != null && protocolModel.Contacts.Any())
            {
                foreach (ProtocolContactModel protocolContactModel in protocolModel.Contacts)
                {
                    Data.Contact contact = FacadeFactory.Instance.ContactFacade.GetById(protocolContactModel.IdContact);
                    if (protocolContactModel.ComunicationType == ComunicationType.Sender)
                    {
                        protInitializer.Senders.Add(new Data.ContactDTO(contact, Data.ContactDTO.ContactType.Address));
                    }
                    else
                    {
                        protInitializer.Recipients.Add(new Data.ContactDTO(contact, Data.ContactDTO.ContactType.Address));
                    }
                }
            }
            return(protInitializer);
        }