Ejemplo n.º 1
0
        // Trata a criação de novos níveis e respectivas relações. Caso se trate
        // de um nível orgânico (estrutural e que esteja associado a uma EP) o
        // nível correspondente deverá já existir e não será por isso criado,
        // será criada apenas a relação.
        private bool handleNewNivel(Form frm, GISADataset.NivelRow parentNivelRow, GISADataset.TipoNivelRelacionadoRow tnrRow)
        {
            frm.Text = "Criar " + tnrRow.Designacao;

            bool successfulSave = true;

            switch (frm.ShowDialog())
            {
            case DialogResult.OK:

                Trace.WriteLine("A criar nível...");

                long           click = DateTime.Now.Ticks;
                string         designacaoUFAssociada = string.Empty;
                PostSaveAction postSaveAction        = null;
                var            nRow   = GisaDataSetHelper.GetInstance().Nivel.AddNivelRow(tnrRow.TipoNivelRow, ((FormAddNivel)frm).txtCodigo.Text.Trim(), "NVL", new byte[] { }, 0);
                var            ndRow  = GisaDataSetHelper.GetInstance().NivelDesignado.AddNivelDesignadoRow(nRow, ((FormAddNivel)frm).txtDesignacao.Text.Trim(), new byte[] { }, 0);
                var            frdRow = GisaDataSetHelper.GetInstance().FRDBase.AddFRDBaseRow(nRow, (GISADataset.TipoFRDBaseRow)(GisaDataSetHelper.GetInstance().TipoFRDBase.Select("ID=" + DomainValuesHelper.stringifyEnumValue(TipoFRDBase.FRDOIRecolha))[0]), "", "", new byte[] { }, 0);
                var            rhRow  = GisaDataSetHelper.GetInstance().RelacaoHierarquica.AddRelacaoHierarquicaRow(nRow, parentNivelRow, tnrRow, null, null, null, null, null, null, null, new byte[] { }, 0);

                //valores por omissão
                var globalConfig = GisaDataSetHelper.GetInstance().GlobalConfig.Cast <GISADataset.GlobalConfigRow>().Single();
                if (globalConfig.ApplyDefaultValues)
                {
                    var sfrdcaRow = GisaDataSetHelper.GetInstance().SFRDCondicaoDeAcesso
                                    .AddSFRDCondicaoDeAcessoRow(frdRow, "", globalConfig.IsCondicaoDeAcessoNull() ? "" : globalConfig.CondicaoDeAcesso,
                                                                globalConfig.IsCondicaoDeReproducaoNull() ? "" : globalConfig.CondicaoDeReproducao, "", new byte[] {}, 0);

                    foreach (GISADataset.ConfigLinguaRow r in globalConfig.GetConfigLinguaRows())
                    {
                        GisaDataSetHelper.GetInstance().SFRDLingua.AddSFRDLinguaRow(sfrdcaRow, r.Iso639Row, new byte[] { }, 0);
                    }

                    foreach (GISADataset.ConfigAlfabetoRow r in globalConfig.GetConfigAlfabetoRows())
                    {
                        GisaDataSetHelper.GetInstance().SFRDAlfabeto.AddSFRDAlfabetoRow(sfrdcaRow, r.Iso15924Row, new byte[] { }, 0);
                    }
                }

                var selectedTipologia = ((FormNivelDocumentalFedora)frm).Tipologia;
                if (selectedTipologia != null)
                {
                    GisaDataSetHelper.GetInstance().IndexFRDCA.AddIndexFRDCARow(frdRow, selectedTipologia.ControloAutRow, -1, new byte[] { }, 0);
                }

                // Só adicionar permissões ao grupo TODOS dos níveis lógicos e a níveis documentais imediatamente
                // abaixo de níveis orgânicos (Documentos soltos e séries); caso se se trate de um nível estrutural
                // controlado, as permissões já foram atribuidas aquando da criação do controlo de autoridade
                if (nRow.IDTipoNivel == TipoNivel.DOCUMENTAL && parentNivelRow.IDTipoNivel == TipoNivel.ESTRUTURAL)
                {
                    var nUpperRow = rhRow == null ? default(GISADataset.NivelRow) : rhRow.NivelRowByNivelRelacaoHierarquicaUpper;
                    PermissoesHelper.AddNewNivelGrantPermissions(nRow, nUpperRow);
                }

                postSaveAction = new PostSaveAction();
                var args = new PersistencyHelper.GenericPostSaveArguments();
                postSaveAction.args             = args;
                postSaveAction.postSaveDelegate = delegate(PersistencyHelper.PostSaveArguments postSaveArgs)
                {
                    if (!postSaveArgs.cancelAction && nRow != null && nRow.RowState != DataRowState.Detached && nRow.RowState != DataRowState.Deleted)
                    {
                        // registar a criação do nivel documental
                        GISADataset.FRDBaseRow   frdDocRow  = null;
                        GISADataset.FRDBaseRow[] frdDocRows = nRow.GetFRDBaseRows();
                        if (frdDocRows.Length > 0)
                        {
                            frdDocRow = frdDocRows[0];
                        }
                        CurrentContext.RaiseRegisterModificationEvent(frdDocRow);

                        PersistencyHelperRule.Current.saveRows(GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao,
                                                               GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao.Cast <GISADataset.FRDBaseDataDeDescricaoRow>().Where(frd => frd.RowState == DataRowState.Added).ToArray(), postSaveArgs.tran);
                    }
                };

                // se se tratar de um (sub)documento é necessário garantir que se trata de um código
                // único dentro da sua série (se constituir série) ou nivel estrutural superior
                PersistencyHelper.ValidateNivelAddAndAssocNewUFPreConcArguments pcArgs = new PersistencyHelper.ValidateNivelAddAndAssocNewUFPreConcArguments();
                PersistencyHelper.SetNewCodigosPreSaveArguments           psArgs       = new PersistencyHelper.SetNewCodigosPreSaveArguments();
                PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments pcArgsNivel  = new PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments();

                pcArgs.argsNivel = pcArgsNivel;

                // dados que serão usados no delegate responsável pela criação do nível documental
                pcArgsNivel.nRowID              = nRow.ID;
                pcArgsNivel.ndRowID             = ndRow.ID;
                pcArgsNivel.rhRowID             = rhRow.ID;
                pcArgsNivel.rhRowIDUpper        = rhRow.IDUpper;
                pcArgsNivel.frdBaseID           = frdRow.ID;
                pcArgsNivel.testOnlyWithinNivel = true;

                // permitir ao delegate selecionar o delegate correspondente ao tipo de nível que se está a criar
                pcArgs.IDTipoNivelRelacionado = tnrRow.ID;

                psArgs.createNewNivelCodigo = false;
                psArgs.createNewUFCodigo    = false;
                psArgs.setNewCodigo         = rhRow.IDTipoNivelRelacionado == TipoNivelRelacionado.SD;
                psArgs.argsNivelDocSimples  = NiveisHelper.AddNivelDocumentoSimplesWithDelegateArgs(nRow.GetNivelDesignadoRows().Single(), rhRow.IDUpper, rhRow.IDTipoNivelRelacionado);

                PersistencyHelper.save(DelegatesHelper.ValidateNivelAddAndAssocNewUF, pcArgs, DelegatesHelper.SetNewCodigos, psArgs, postSaveAction);
                if (!pcArgsNivel.successful)
                {
                    successfulSave = false;
                    MessageBox.Show(pcArgsNivel.message, "Criação de unidade de descrição", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (parentNivelRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].TipoNivelRelacionadoRow.ID == TipoNivelRelacionado.SR)
                {
                    GisaDataSetHelper.HoldOpen ho = new GisaDataSetHelper.HoldOpen(GisaDataSetHelper.GetConnection());
                    try
                    {
                        DBAbstractDataLayer.DataAccessRules.FRDRule.Current.LoadSFRDAvaliacaoData(GisaDataSetHelper.GetInstance(), parentNivelRow.ID, ho.Connection);
                    }
                    finally
                    {
                        ho.Dispose();
                    }
                }

                PersistencyHelper.cleanDeletedData(new List <TableDepthOrdered.TableCloudType>(new TableDepthOrdered.TableCloudType[] { PersistencyHelper.determinaNuvem("RelacaoHierarquica"), PersistencyHelper.determinaNuvem("FRDBase") }));

                if (!successfulSave)
                {
                    return(successfulSave);
                }

                GISA.Search.Updater.updateNivelDocumentalComProdutores(nRow.ID);
                GISA.Search.Updater.updateNivelDocumental(nRow.ID);

                this.nivelNavigator1.AddNivel(nRow);

                Debug.WriteLine("<<A criar nível...>> " + new TimeSpan(DateTime.Now.Ticks - click).ToString());
                break;

            case DialogResult.Cancel:
                successfulSave = false;
                break;
            }

            return(successfulSave);
        }
Ejemplo n.º 2
0
        private void RemoveNivel()
        {
            GISADataset.NivelRow nUpperRow          = null;
            GISADataset.RelacaoHierarquicaRow rhRow = null;
            GISADataset.NivelRow nRow = null;


            nRow = this.nivelNavigator1.SelectedNivel;
            // Verificar se a relacção hierárquica ainda é a mesma apresentada na interface (se o
            // utilizador estiver a ver a lista que contem o nível a apagar e entretanto outro utilizador
            // o ter colocado noutro ponto da árvore, a relação hierárquica presente em memória deixa
            // de corresponder com aquela que é apresentada na interface quando esse nível é selecionado;
            // quando o nível é selecionado a informação no DataSet de trabalho é actualizado mas não
            // actualiza a interface)
            if (GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", nRow.ID, this.nivelNavigator1.ContextBreadCrumbsPathID)).Length > 0)
            {
                rhRow = (GISADataset.RelacaoHierarquicaRow)(GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", nRow.ID, this.nivelNavigator1.ContextBreadCrumbsPathID))[0]);
            }
            else
            {
                MessageBox.Show("Esta operação não pode ser concluída pelo facto de a localização na estrutura " + System.Environment.NewLine + "do nível selecionado ter sido alterada por outro utilizador.", "Eliminar Nível", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            nUpperRow = (GISADataset.NivelRow)(GisaDataSetHelper.GetInstance().Nivel.Select(string.Format("ID={0}", this.nivelNavigator1.ContextBreadCrumbsPathID))[0]);

            var assocODs = FedoraHelper.GetAssociatedODsDetailsMsg(nRow.ID);

            if (assocODs.Length > 0)
            {
                FormDeletionReport form = new FormDeletionReport();
                form.Text         = "Eliminação de unidade de informação";
                form.Interrogacao = "A unidade de informação selecionada tem objeto(s) digital(ais) associado(s). " + System.Environment.NewLine +
                                    "Se eliminar esta unidade de informação, os objeto(s) digital(ais) " + System.Environment.NewLine + " também serão eliminado(s)." + System.Environment.NewLine +
                                    "Pretende continuar?";
                form.Detalhes = assocODs;

                if (form.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
            }
            else if (MessageBox.Show("Tem a certeza que deseja eliminar o nível selecionado?", "Eliminação de relação", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }

            if (!FedoraHelper.CanDeleteODsAssociated2UI(nRow, out objetoDigital))
            {
                return;
            }

            Trace.WriteLine("A apagar nível...");

            if (TipoNivel.isNivelDocumental(nRow) && TipoNivel.isNivelOrganico(nUpperRow))
            {
                // Verificar que existem várias relações hierárquicas deste
                // nível documental a entidades produtoras superiores. Nesse
                // caso deverá ser removida a relação, caso contrário, se não
                // existirem subníveis documentais, será eliminado o próprio
                // nível(documental)
                int numRHs = nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica().Length;
                if (numRHs > 1)
                {
                    if (MessageBox.Show(
                            "Por favor tenha em atenção que são vários os produtores deste " + System.Environment.NewLine +
                            "nível documental. O nível documental propriamente dito não " + System.Environment.NewLine +
                            "será eliminado, apenas a sua relação ao nível orgânico " + System.Environment.NewLine +
                            "superior o será.", "Eliminação de relação", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                    {
                        return;
                    }

                    ((frmMain)TopLevelControl).EnterWaitMode();

                    CurrentContext.RaiseRegisterModificationEvent(nRow.GetFRDBaseRows()[0]);

                    PersistencyHelper.canDeleteRHRowPreConcArguments args = new PersistencyHelper.canDeleteRHRowPreConcArguments();
                    args.nRowID       = nRow.ID;
                    args.nUpperRowID  = nUpperRow.ID;
                    args.rhRowID      = rhRow.ID;
                    args.rhRowIDUpper = rhRow.IDUpper;
                    PersistencyHelper.SaveResult successfulSave = PersistencyHelper.save(DelegatesHelper.verifyIfCanDeleteRH, args);
                    PersistencyHelper.cleanDeletedData(PersistencyHelper.determinaNuvem("RelacaoHierarquica"));
                    if (args.deleteSuccessful)
                    {
                        if (successfulSave == PersistencyHelper.SaveResult.successful)
                        {
                            List <string> IDNiveis = new List <string>();
                            IDNiveis.Add(args.nRowID.ToString());
                            GISA.Search.Updater.updateNivelDocumental(IDNiveis);
                            GISA.Search.Updater.updateNivelDocumentalComProdutores(nRow.ID);
                        }
                        this.nivelNavigator1.RemoveSelectedLVItem();
                    }
                    else
                    {
                        MessageBox.Show(args.message, "Eliminação de relação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    ((frmMain)TopLevelControl).LeaveWaitMode();
                }
                else if (numRHs == 1)
                {
                    // Verificar que não existem subníveis documentais
                    int numSubRHs = GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("IDUpper={0}", nRow.ID)).Length;
                    if (numSubRHs > 0)
                    {
                        MessageBox.Show("Só é possível eliminar os níveis que não tenham outros directamente associados", "Eliminação de relação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        if (MessageBox.Show(
                                "Por favor tenha em atenção que este nível documental é produzido" + System.Environment.NewLine +
                                "por apenas uma entidade. Ao remover esta relação será perdida " + System.Environment.NewLine +
                                "não só a relação como o nível documental propriamente dito.", "Eliminação de relação", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                        {
                            return;
                        }

                        ((frmMain)TopLevelControl).EnterWaitMode();

                        CurrentContext.RaiseRegisterModificationEvent(nRow.GetFRDBaseRows()[0]);

                        PersistencyHelper.canDeleteRHRowPreConcArguments argsPca = new PersistencyHelper.canDeleteRHRowPreConcArguments();
                        argsPca.nRowID       = nRow.ID;
                        argsPca.nUpperRowID  = nUpperRow.ID;
                        argsPca.rhRowID      = 0;
                        argsPca.rhRowIDUpper = 0;
                        PersistencyHelper.DeleteIDXPreSaveArguments argsPsa = new PersistencyHelper.DeleteIDXPreSaveArguments();
                        argsPsa.ID = nRow.ID;

                        // actualizar objecto digital caso exista
                        var preTransactionAction = new PreTransactionAction();
                        var args = new PersistencyHelper.FedoraIngestPreTransactionArguments();
                        preTransactionAction.args = args;

                        preTransactionAction.preTransactionDelegate = delegate(PersistencyHelper.PreTransactionArguments preTransactionArgs)
                        {
                            bool   ingestSuccess = true;
                            string msg           = null;

                            var odsToIngest = FedoraHelper.DeleteObjDigital(nRow);
                            odsToIngest.ForEach(od => ingestSuccess &= SessionHelper.AppConfiguration.GetCurrentAppconfiguration().FedoraHelperSingleton.Ingest(od, out msg));

                            preTransactionArgs.cancelAction = !ingestSuccess;
                            preTransactionArgs.message      = msg;
                        };

                        PersistencyHelper.SaveResult successfulSave = PersistencyHelper.save(DelegatesHelper.verifyIfCanDeleteRH, argsPca, Nivel.DeleteNivelXInDataBase, argsPsa, preTransactionAction);
                        if (argsPca.deleteSuccessful)
                        {
                            if (successfulSave == PersistencyHelper.SaveResult.successful)
                            {
                                List <string> IDNiveis = new List <string>();
                                IDNiveis.Add(nRow.ID.ToString());
                                GISA.Search.Updater.updateNivelDocumental(IDNiveis);
                                GISA.Search.Updater.updateNivelDocumentalComProdutores(nRow.ID);
                            }
                            this.nivelNavigator1.RemoveSelectedLVItem();
                        }
                        else
                        {
                            // se o nível a eliminar se tratar de uma série ou documento solto mas que
                            // por motivos de conflito de concorrência não foi possível executar,
                            // o refrescamento dos botões é feito tendo como o contexto o próprio
                            // nível que se pretendeu eliminar para desta forma o estado dos mesmos
                            // estar correcta (caso contrário o estado dos botões referir-se-ia a
                            // não haver qualquer item selecionado
                            MessageBox.Show(argsPca.message, "Eliminação de relação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            UpdateToolBarButtons(this.nivelNavigator1.SelectedItems[0]);
                        }
                        PersistencyHelper.cleanDeletedData(new List <TableDepthOrdered.TableCloudType>(new TableDepthOrdered.TableCloudType[] { PersistencyHelper.determinaNuvem("RelacaoHierarquica"), PersistencyHelper.determinaNuvem("FRDBase"), PersistencyHelper.determinaNuvem("ObjetoDigital") }));

                        ((frmMain)TopLevelControl).LeaveWaitMode();
                    }
                }
                else
                {
                    Debug.Assert(false, "Should never happen. There must be a relation with an upper Nivel.");
                }
            }
            else
            {
                // Entre todos os outros tipos de nível proceder normalmente
                if ((nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].IDTipoNivelRelacionado == TipoNivelRelacionado.D ||
                     nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].IDTipoNivelRelacionado == TipoNivelRelacionado.SD) &&
                    NiveisHelper.NivelFoiMovimentado(nRow.ID))
                {
                    if (MessageBox.Show(
                            "Por favor tenha em atenção que este nível documental já foi " + System.Environment.NewLine +
                            "requisitado/devolvido. Ao remover nível documental serão perdidos " + System.Environment.NewLine +
                            "todos os seus registos referentes a requisições e devoluções.", "Eliminação de nível documental", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                ((frmMain)TopLevelControl).EnterWaitMode();

                CurrentContext.RaiseRegisterModificationEvent(nRow.GetFRDBaseRows()[0]);

                PersistencyHelper.canDeleteRHRowPreConcArguments argsPca = new PersistencyHelper.canDeleteRHRowPreConcArguments();
                argsPca.nRowID       = nRow.ID;
                argsPca.nUpperRowID  = nUpperRow.ID;
                argsPca.rhRowID      = 0;
                argsPca.rhRowIDUpper = 0;
                PersistencyHelper.DeleteIDXPreSaveArguments argsPsa = new PersistencyHelper.DeleteIDXPreSaveArguments();
                argsPsa.ID = nRow.ID;

                // actualizar objecto digital caso exista
                var preTransactionAction = new PreTransactionAction();
                var args = new PersistencyHelper.FedoraIngestPreTransactionArguments();
                preTransactionAction.args = args;

                preTransactionAction.preTransactionDelegate = delegate(PersistencyHelper.PreTransactionArguments preTransactionArgs)
                {
                    bool   ingestSuccess = true;
                    string msg           = null;

                    var odsToIngest = FedoraHelper.DeleteObjDigital(nRow);
                    odsToIngest.ForEach(od => ingestSuccess &= SessionHelper.AppConfiguration.GetCurrentAppconfiguration().FedoraHelperSingleton.Ingest(od, out msg));

                    preTransactionArgs.cancelAction = !ingestSuccess;
                    preTransactionArgs.message      = msg;
                };

                PersistencyHelper.SaveResult successfulSave = PersistencyHelper.save(DelegatesHelper.verifyIfCanDeleteRH, argsPca, Nivel.DeleteNivelXInDataBase, argsPsa, preTransactionAction);
                PersistencyHelper.cleanDeletedData(new List <TableDepthOrdered.TableCloudType>(new TableDepthOrdered.TableCloudType[] { PersistencyHelper.determinaNuvem("RelacaoHierarquica"), PersistencyHelper.determinaNuvem("FRDBase") }));
                if (argsPca.deleteSuccessful)
                {
                    if (successfulSave == PersistencyHelper.SaveResult.successful)
                    {
                        List <string> IDNiveis = new List <string>();
                        IDNiveis.Add(argsPsa.ID.ToString());
                        GISA.Search.Updater.updateNivelDocumental(IDNiveis);
                        if (nRow.RowState == DataRowState.Detached)
                        {
                            GISA.Search.Updater.updateNivelDocumentalComProdutores(argsPsa.ID);
                        }
                        else
                        {
                            GISA.Search.Updater.updateNivelDocumentalComProdutores(nRow.ID);
                        }

                        this.nivelNavigator1.RemoveSelectedLVItem();
                    }
                }
                else
                {
                    MessageBox.Show(argsPca.message, "Eliminação de relação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                ((frmMain)TopLevelControl).LeaveWaitMode();
            }

            UpdateToolBarButtons();
        }