예제 #1
0
        public object Execute(ContextDataObject context, Entity document)
        {
            /* **************************************** */
            /* **************************************** */
            /*          ADD YOUR CODE HERE              */
            ErpBS bsERP = new ErpBS();

            try {
                if (!context.Parameters.ContainsKey("TipoPlataforma"))
                {
                    throw new Exception("TipoPlataforma inválido");
                }

                EnumTipoPlataforma tipoPlataforma;
                if (!Enum.TryParse <EnumTipoPlataforma>((string)context.Parameters["TipoPlataforma"], out tipoPlataforma))
                {
                    throw new Exception("TipoPlataforma inválido");
                }

                try
                {
                    bsERP.AbreEmpresaTrabalho(tipoPlataforma, context.Company, context.Username, context.Password);
                }
                catch (Exception e)
                {
                    throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
                }
                GcpBEDocumentoCompra purchaseOrder = new GcpBEDocumentoCompra();
                purchaseOrder.set_Tipodoc("ECF");
                purchaseOrder.set_Serie("A");
                purchaseOrder.set_TipoEntidade("F");
                purchaseOrder.set_Entidade(document.Attributes.Supplier);
                purchaseOrder.set_NumDocExterno("0");
                purchaseOrder.set_Observacoes("Documento gerado no portal OMNIA: Pedido de Encomenda " + document.NumberSerieCode + "/" + document.Number);
                purchaseOrder.set_DataCarga(document.DateCreated.ToShortDateString());
                purchaseOrder.set_DataDescarga(document.DateCreated.ToShortDateString());

                bsERP.Comercial.Compras.PreencheDadosRelacionados(purchaseOrder);
                foreach (var line in document.Commitments.GoodsPurchaseRequest)
                {
                    bsERP.Comercial.Compras.AdicionaLinha(purchaseOrder, line.Resource, line.Quantity, "A1", "", line.Amount);
                }

                bsERP.Comercial.Compras.Actualiza(purchaseOrder);

                bsERP.FechaEmpresaTrabalho();

                return(new ScriptResponse {
                    Message = "Integrado documento " + purchaseOrder.get_Tipodoc() + " " + purchaseOrder.get_Serie() + "/" + purchaseOrder.get_NumDoc()
                });
            } catch (Exception ex) {
                bsERP.FechaEmpresaTrabalho();

                throw ex;
            }
        }
예제 #2
0
        /// <summary>
        /// Return a list of companies where the credit limit of the given customer is exceeded orelse has been blocked.
        /// </summary>
        /// <param name="strCustomer">Customer to be analised</param>
        /// <returns>List<String></String></returns>
        internal static List <String> CreditLimitExceeded(ERPContext ERPContext, String strCustomer)
        {
            List <String> companiesList = new List <String>();
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(ERPContext);

            foreach (string company in groupCompanies.Keys)
            {
                ErpBS currentCompany = new ErpBS();

                currentCompany.AbreEmpresaTrabalho(
                    StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    company,
                    Properties.Settings.Default.User,    //ERPContext.BSO.Contexto.ObjUtilizador.Codigo,
                    Properties.Settings.Default.Password //ERPContext.BSO.Contexto.ObjUtilizador.Password
                    );

                if ((currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "TipoCred") == "2") ||
                    (currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "limitecred") < currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "totaldeb")))
                {
                    companiesList.Add(company);
                }

                currentCompany.FechaEmpresaTrabalho();
            }

            return(companiesList);
        }
예제 #3
0
        public ScriptResponse Execute(ContextDataObject context, string query)
        {
            ErpBS bsERP = new ErpBS();

            if (!context.Parameters.ContainsKey("TipoPlataforma"))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            EnumTipoPlataforma tipoPlataforma;

            if (!Enum.TryParse <EnumTipoPlataforma>((string)context.Parameters["TipoPlataforma"], out tipoPlataforma))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            try
            {
                bsERP.AbreEmpresaTrabalho(tipoPlataforma, context.Company, context.Username, context.Password);
            }
            catch (Exception e)
            {
                throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
            }

            StdBELista queryResults = bsERP.Consulta(query);

            int numLinhas  = queryResults.NumLinhas();
            int numColunas = queryResults.NumColunas();

            string[] headers = new string[numColunas];
            for (short i = 0; i < numColunas; i++)
            {
                headers[i] = queryResults.Nome(i);
            }

            object[,] data = new object[numLinhas, numColunas];
            for (short i = 0; i < numLinhas; i++)
            {
                for (short j = 0; j < numColunas; j++)
                {
                    var nome = headers[j];
                    data[i, j] = queryResults.Valor(nome);
                }
                queryResults.Seguinte();
            }

            QueryResult response = new QueryResult()
            {
                Headers = headers,
                Data    = data
            };

            bsERP.FechaEmpresaTrabalho();

            return(new ScriptResponse
            {
                Object = response
            });
        }
        /// <summary>
        /// Update the Item in the group companies
        /// </summary>
        /// <param name="oERPContext"></param>
        /// <param name="Artigo"></param>
        /// <returns>List<String> of the updated companies</returns>
        internal static List <String> UpdateItem_GroupCompanies(ERPContext oERPContext, String Item)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string company in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    company,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                //Create or update the item
                BasBEArtigo      oItem       = oERPContext.BSO.Base.Artigos.Edita(Item);
                BasBEArtigoMoeda oItemPrices = oERPContext.BSO.Base.ArtigosPrecos.Edita(Item, "EUR", oERPContext.BSO.Base.Artigos.DaValorAtributo(Item, "UnidadeBase"));
                if (!oCompany.Base.Artigos.Existe(Item))
                {
                    oItem.EmModoEdicao       = false;
                    oItemPrices.EmModoEdicao = false;
                }
                oCompany.Base.Artigos.Actualiza(oItem);
                oCompany.Base.ArtigosPrecos.Actualiza(oItemPrices);
                updatedCompanies.Add(company);

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
예제 #5
0
        /// <summary>
        /// Metodo para inicializar o motor do primavera
        /// </summary>
        /// <param name="tipoPlataforma"> 0 - Executiva, 1- Profissional</param>
        /// <param name="codEmpresa"></param>
        /// <param name="codUsuario"></param>
        /// <param name="password"></param>
        /// <remarks></remarks>
        public PrimaveraResultStructure AbreEmpresaPrimavera(int tipoPlataforma, string codEmpresa, string codUsuario, string password)
        {
            PrimaveraResultStructure result = new PrimaveraResultStructure();

            try
            {
                this.tipoPlataforma = tipoPlataforma;
                this.codUsuario     = codUsuario;
                this.codEmpresa     = codEmpresa;
                this.password       = password;

                if (_erpBs == null)
                {
                    _erpBs = new ErpBS();
                }
                else
                {
                    _erpBs.FechaEmpresaTrabalho();
                }

                _erpBs.AbreEmpresaTrabalho(tipoPlataforma == 0 ? EnumTipoPlataforma.tpEmpresarial : EnumTipoPlataforma.tpProfissional,
                                           codEmpresa, codUsuario, password, null, "DEFAULT", true);

                result.codigo    = 0;
                result.descricao = string.Format("Empresa {0} - {1} Aberta Com Sucesso", _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome);
                Console.WriteLine(String.Format("[{0}] Empresa {1} - {2} Aberta Com Sucesso", DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome));

                return(result);
            }
            catch (Exception ex)
            {
                result.codigo    = 3;
                result.descricao = ex.Message;
                Console.WriteLine(String.Format("[{0}] Erro a abrir a Empresa {1} - {2} devido a: {3}", DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome, ex.Message));

                return(result);
            }
        }
        internal static List <String> UpdateEntity(ERPContext oERPContext, string EntityType, string Entity)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string groupCompany in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                //get the last exercise (to create the entity accounts for each exercise)
                int lastYear = oERPContext.BSO.Contabilidade.ExerciciosCBL.DaUltimoAno();

                switch (EntityType)
                {
                case "C":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Clientes.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBECliente objNewEntity = oERPContext.BSO.Base.Clientes.Edita(Entity);
                        if (!oCompany.Base.Clientes.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.Clientes.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPClientes, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPClientes);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "F":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Fornecedores.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBEFornecedor objNewEntity = oERPContext.BSO.Base.Fornecedores.Edita(Entity);
                        if (!oCompany.Base.Fornecedores.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.Fornecedores.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPFornecedores, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPFornecedores);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "R":
                case "D":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.OutrosTerceiros.DaValorAtributo(Entity, EntityType, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBEOutroTerceiro objNewEntity = oERPContext.BSO.Base.OutrosTerceiros.Edita(Entity);
                        if (!oCompany.Base.OutrosTerceiros.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.OutrosTerceiros.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPOutrosTerceiros, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPOutrosTerceiros);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "E":
                    if (Convert.ToBoolean(oERPContext.BSO.CRM.EntidadesExternas.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        CrmBEEntidadeExterna objNewEntity = oERPContext.BSO.CRM.EntidadesExternas.Edita(Entity);
                        if (!oCompany.CRM.EntidadesExternas.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.CRM.EntidadesExternas.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                default:
                    break;
                }

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
        internal static List <String> RemoveEntity(ERPContext oERPContext, string EntityType, string Entity)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string groupCompany in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                switch (EntityType)
                {
                case "C":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Clientes.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.Clientes.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "F":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Fornecedores.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.Fornecedores.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "R":
                case "D":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.OutrosTerceiros.DaValorAtributo(Entity, EntityType, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.OutrosTerceiros.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "E":
                    if (Convert.ToBoolean(oERPContext.BSO.CRM.EntidadesExternas.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.CRM.EntidadesExternas.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                default:
                    break;
                }

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
        //Method that executes the query in the external system.
        private ScriptResponse executeQuery(ContextData context, Entity document, string query)
        {
            ErpBS bsERP = new ErpBS();

            if (context.ExternalSystems == null || context.ExternalSystems.Count == 0)
            {
                throw new Exception("External System em falta");
            }

            var externalSystem = context.ExternalSystems.FirstOrDefault().Value;

            if (!externalSystem.Parameters.ContainsKey("TipoPlataforma"))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            EnumTipoPlataforma tipoPlataforma;

            if (!Enum.TryParse <EnumTipoPlataforma>((string)externalSystem.Parameters["TipoPlataforma"], out tipoPlataforma))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            try
            {
                bsERP.AbreEmpresaTrabalho(tipoPlataforma, externalSystem.Code, (string)externalSystem.Parameters["Username"], (string)externalSystem.Parameters["Password"]);
            }
            catch (Exception e)
            {
                throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
            }

            StdBELista queryResults = bsERP.Consulta(query);

            int numLinhas  = queryResults.NumLinhas();
            int numColunas = queryResults.NumColunas();

            string[] headers = new string[numColunas];
            for (short i = 0; i < numColunas; i++)
            {
                headers[i] = queryResults.Nome(i);
            }

            object[,] data = new object[numLinhas, numColunas];
            for (short i = 0; i < numLinhas; i++)
            {
                for (short j = 0; j < numColunas; j++)
                {
                    var nome = headers[j];
                    data[i, j] = queryResults.Valor(nome);
                }
                queryResults.Seguinte();
            }

            QueryResult response = new QueryResult()
            {
                Headers = headers,
                Data    = data
            };

            bsERP.FechaEmpresaTrabalho();

            return(new ScriptResponse
            {
                Result = response
            });
        }
예제 #9
0
        /// <summary>
        /// Processes before open the company
        /// </summary>
        /// <param name="Cancel"></param>
        internal static void BeforeOpenCompany(ERPContext oERPContext, ref Boolean Cancel)
        {
            String             groupCategory = GetCompanyCategory(ref oERPContext);
            StdBSDialogoEspera oDialog;

            //Validation: the current company belongs to a category
            if (string.IsNullOrEmpty(groupCategory))
            {
                Cancel = true;
                oERPContext.PSO.Dialogos.MostraAviso(
                    "A empresa actual não está inserida em nenhuma categoria no administrador.",
                    StdPlatBS100.StdBSTipos.IconId.PRI_Critico,
                    "É necessário associar esta empresa à categoria onde estão inseridas as restantes empresas do grupo.");
                return;
            }

            oDialog = oERPContext.PSO.Dialogos.MostraDialogoEspera(
                sMensagem: "A processar manutenções nas empresas do grupo.",
                iNumProgressBars: 2,
                eIcon: StdBSTipos.IconId.PRI_Informativo,
                eAnim: StdBSTipos.AnimId.PRI_AviCalculos,
                sLabel1: "Calcular lista de empresas...",
                sLabel2: "Analisar lista de operações...");


            //Validation: there are further companies in the group. If not nothing should happen.
            Dictionary <String, String> groupCompanies = GetGroupCompanies(oERPContext);

            if (groupCompanies.Count == 0)
            {
                return; // No message is needed
            }


            //Validations by company
            int processedCompanies = 0;

            foreach (String groupCompany in groupCompanies.Keys)
            {
                oDialog.SetCaption(string.Format("A processar: {0}.", groupCompany), 1);

                ErpBS oCompany = new ErpBS();
                oCompany.AbreEmpresaTrabalho(
                    StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);
                oDialog.ProgressBar2 = 2;

                //Check DATA MODEL
                oDialog.SetCaption("A verificar o modelo de dados...", 2);
                DataUpgrade(ref oCompany);
                oDialog.ProgressBar2 = 50;

                //Check Projects (not implemented - example for further entity validations)
                oDialog.SetCaption("A actualizar Projectos...", 2);
                //Do something
                oDialog.ProgressBar2 = 80;

                //Check default data (not implemented - example for defaults mastering)
                oDialog.SetCaption("A actualizar dados predefinidos...", 2);
                //Do something
                oDialog.ProgressBar2 = 100;


                //Final by company operations
                oCompany.FechaEmpresaTrabalho();
                oDialog.SetCaption("", 2);
                processedCompanies  += 1;
                oDialog.ProgressBar1 = Convert.ToInt32(((processedCompanies * 100) / groupCompanies.Count));
                oDialog.ProgressBar2 = 0;
            }

            oDialog.Termina();
        }
        public ScriptResponse Execute(ContextData context, Entity document, Dictionary <string, object> parameters)
        {
            /* **************************************** */
            /* **************************************** */
            /*          ADD YOUR CODE HERE              */
            ErpBS bsERP          = new ErpBS();
            var   externalSystem = context.ExternalSystems.FirstOrDefault().Value;

            try
            {
                if (!externalSystem.Parameters.ContainsKey("TipoPlataforma"))
                {
                    throw new Exception("TipoPlataforma invalido");
                }

                EnumTipoPlataforma tipoPlataforma;
                if (!Enum.TryParse <EnumTipoPlataforma>((string)externalSystem.Parameters["TipoPlataforma"], out tipoPlataforma))
                {
                    throw new Exception("TipoPlataforma invalido");
                }

                try
                {
                    bsERP.AbreEmpresaTrabalho(tipoPlataforma, externalSystem.Code, (string)externalSystem.Parameters["Username"], (string)externalSystem.Parameters["Password"]);
                }
                catch (Exception e)
                {
                    throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
                }

                string str       = externalSystem.Parameters["0"].ToString();
                int    first     = str.IndexOf("Commitments.GoodsPurchaseRequest[") + "Commitments.GoodsPurchaseRequest[".Length;
                int    last      = str.LastIndexOf("].ERPCode");
                int    commIndex = int.Parse(str.Substring(first, last - first));

                StdBELista queryResults = bsERP.Consulta($"SELECT Nome,Pais FROM Fornecedores WHERE Fornecedor='{document.Commitments.GoodsPurchaseRequest[commIndex].Attributes.ERPCode}'");

                int numLinhas  = queryResults.NumLinhas();
                int numColunas = queryResults.NumColunas();

                string[] headers = new string[numColunas];
                for (short i = 0; i < numColunas; i++)
                {
                    headers[i] = queryResults.Nome(i);
                }

                object[,] data = new object[numLinhas, numColunas];
                for (short i = 0; i < numLinhas; i++)
                {
                    for (short j = 0; j < numColunas; j++)
                    {
                        var nome = headers[j];
                        data[i, j] = queryResults.Valor(nome);
                    }
                    queryResults.Seguinte();
                }

                QueryResult response = new QueryResult()
                {
                    Headers         = headers,
                    Data            = data,
                    NumberOfRecords = numLinhas
                };

                bsERP.FechaEmpresaTrabalho();

                return(new ScriptResponse
                {
                    Result = response
                });
            }
            catch (Exception ex)
            {
                bsERP.FechaEmpresaTrabalho();

                throw ex;
            }
        }
        /// <summary>
        /// Import a purchases document.
        /// </summary>
        /// <param name="oERPContext"></param>
        /// <param name="Company"></param>
        /// <param name="IdDoc"></param>
        /// <returns>The reference of the created document or the error text.</returns>
        internal static Tuple <string, string> ImportPurchasesDocument(ERPContext oERPContext, String Company, String IdDoc)
        {
            Tuple <string, string> retValue = new Tuple <string, string>(String.Empty, String.Empty);
            ErpBS  oCompany   = new ErpBS();
            string strErrWarn = string.Empty;

            try
            {
                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    Company,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                CmpBEDocumentoCompra sourceDocument = oCompany.Compras.Documentos.EditaID(IdDoc);
                String targetDocumentType           = oCompany.Compras.TabCompras.DaValorAtributo(sourceDocument.Tipodoc, "CDU_DocDestino");


                //Error if the target document not exists in the target company
                if (!oERPContext.BSO.Vendas.TabVendas.Existe(targetDocumentType))
                {
                    throw new Exception(String.Format("O tipo de documento {0} não existe na empresa atual.", targetDocumentType));
                }
                VndBETabVenda salesTable = oERPContext.BSO.Vendas.TabVendas.Edita(targetDocumentType);


                //NEW DOCUMENT
                VndBEDocumentoVenda targetDocument = new VndBEDocumentoVenda();
                targetDocument.Filial       = "000";
                targetDocument.Serie        = oERPContext.BSO.Base.Series.DaSerieDefeito("V", targetDocumentType);
                targetDocument.Tipodoc      = targetDocumentType;
                targetDocument.TipoEntidade = "C";

                //Error if the entity doesnt exists in the target company
                if (!oERPContext.BSO.Base.Clientes.Existe(Company))
                {
                    throw new Exception(String.Format("O cliente {0} não existe na empresa atual.", Company));
                }
                targetDocument.Entidade = Company;

                targetDocument.DataDoc = sourceDocument.DataDoc;
                int preencheDadosTodos = (int)BasBETiposGcp.PreencheRelacaoVendas.vdDadosTodos;
                targetDocument = oERPContext.BSO.Vendas.Documentos.PreencheDadosRelacionados(targetDocument, ref preencheDadosTodos);
                if (targetDocument.DataVenc == default(DateTime))
                {
                    targetDocument.DataVenc = sourceDocument.DataVenc;
                }
                if (string.IsNullOrEmpty(targetDocument.CondPag))
                {
                    targetDocument.CondPag = sourceDocument.CondPag;
                }
                if (string.IsNullOrEmpty(targetDocument.ModoPag))
                {
                    targetDocument.ModoPag = sourceDocument.ModoPag;
                }
                targetDocument.DescFinanceiro = sourceDocument.DescFinanceiro;
                targetDocument.DescEntidade   = sourceDocument.DescFornecedor;
                targetDocument.CamposUtil["CDU_Exportado"].Valor = 1;

                //NEW DOCUMENT DETAILS
                foreach (CmpBELinhaDocumentoCompra detailSourceDocument in sourceDocument.Linhas)
                {
                    double quantity                = detailSourceDocument.Quantidade;
                    string targetWarehouse         = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "ArmazemSugestao") ?? detailSourceDocument.Armazem;
                    string targetWarehouseLocation = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "LocalizacaoSugestao") ?? detailSourceDocument.Localizacao;
                    targetDocument = oERPContext.BSO.Vendas.Documentos.AdicionaLinha(
                        targetDocument,
                        detailSourceDocument.Artigo,
                        ref quantity,
                        ref targetWarehouse,
                        ref targetWarehouseLocation,
                        detailSourceDocument.PrecUnit,
                        detailSourceDocument.Desconto1);
                }

                //SAVE
                string settlementSeries = string.Empty;
                if (!oERPContext.BSO.Vendas.Documentos.ValidaActualizacao(targetDocument, salesTable, ref settlementSeries, ref strErrWarn))
                {
                    throw new Exception(strErrWarn);
                }
                else
                {
                    oERPContext.BSO.Vendas.Documentos.Actualiza(targetDocument, ref strErrWarn);

                    retValue = Tuple.Create <string, string>(
                        string.Format("{0} {1}/{2}", targetDocument.Tipodoc, targetDocument.Serie, targetDocument.NumDoc.ToString()),
                        strErrWarn);

                    oCompany.DSO.ExecuteSQL(string.Format("UPDATE CabecCompras SET CDU_Exportado=1 WHERE ID='{0}'", sourceDocument.ID));
                    //TODO: Eliminar (foi adicionado porque o objeto não estava a gravar os valores dos CDUs)
                    oERPContext.BSO.DSO.ExecuteSQL(string.Format("UPDATE CabecDoc SET CDU_Exportado=1 WHERE ID='{0}'", targetDocument.ID));
                }
            }
            catch (Exception e)
            {
                retValue = Tuple.Create <string, string>("ERRO", e.Message);
            }
            finally
            {
                if (oCompany != null)
                {
                    oCompany.FechaEmpresaTrabalho();
                }
            }

            return(retValue);
        }