예제 #1
0
        public bool Next(int limit = -1)
        {
            // If it not has line
            if (!HasLine)
            {
                return(false);
            }


            if (IsFirstLine)
            {
                IsFirstLine = false;
                return(true);
            }

            if (++Position >= limit && limit > 0)
            {
                k.Diagnostic.Warning(this.GetHashCode(), Track, "The query is limited to show {0} lines.", limit);

                RS = null;
                return(false);
            }

            RS.MoveNext();

            if (!RS.EoF)
            {
                return(true);
            }
            else
            {
                RS = null;
                return(false);
            }
        }
예제 #2
0
        public List <string> GetALLRequest()
        {
            SAPbobsCOM.Recordset lObjRecordSet = null;

            string        lStrQuery   = "";
            List <string> lLstRequest = new List <string>();

            try
            {
                lObjRecordSet = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);


                lStrQuery = "select U_RequestId from [dbo].[@UG_PE_WS_PERE] ";
                lObjRecordSet.DoQuery(lStrQuery);

                if (lObjRecordSet.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordSet.RecordCount; i++)
                    {
                        lLstRequest.Add(lObjRecordSet.Fields.Item("U_RequestId").Value.ToString());
                        lObjRecordSet.MoveNext();
                    }
                }
                return(lLstRequest);
            }
            catch (Exception lObjException)
            {
                throw new QueryException(lObjException.Message, lObjException);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordSet);
            }
        }
예제 #3
0
        public IList <AccountDTO> GetBankAccounts(string pStrBankCode)
        {
            SAPbobsCOM.Recordset lObjResults  = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            IList <AccountDTO>   lLstObjBanks = new List <AccountDTO>();

            try
            {
                string lStrQuery = this.GetSQL("GetBankAccounts").InjectSingleValue("BankCode", pStrBankCode);
                lObjResults.DoQuery(lStrQuery);
                if (lObjResults.RecordCount > 0)
                {
                    for (int i = 0; i < lObjResults.RecordCount; i++)
                    {
                        AccountDTO lObjAccount = new AccountDTO();
                        lObjAccount.BankCode  = lObjResults.GetColumnValue <string>("BankCode");
                        lObjAccount.Account   = lObjResults.GetColumnValue <string>("Account");
                        lObjAccount.Branch    = lObjResults.GetColumnValue <string>("Branch");
                        lObjAccount.GLAccount = lObjResults.GetColumnValue <string>("GLAccount");
                        lLstObjBanks.Add(lObjAccount);
                        lObjResults.MoveNext();
                    }
                }
                return(lLstObjBanks);
            }
            catch (Exception e)
            {
                LogService.WriteError("GetBankAccounts (GetFilterssVouchers): " + e.Message);
                LogService.WriteError(e);
                return(lLstObjBanks);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjResults);
            }
        }
예제 #4
0
        public static List <int> getTransactionList()
        {
            SAPbobsCOM.Recordset objRSControl = null;
            List <int>           lTransaction = null;
            string strSQL = "";

            try
            {
                lTransaction = new List <int>();
                strSQL       = Settings._BalanceTerceros.getTransactionList;
                objRSControl = MainObject.Instance.B1Company.GetBusinessObject(BoObjectTypes.BoRecordset);
                if (objRSControl != null)
                {
                    objRSControl.DoQuery(strSQL);
                    if (objRSControl.RecordCount > 0)
                    {
                        while (!objRSControl.EoF)
                        {
                            int intTransId = objRSControl.Fields.Item(0).Value;
                            if (!lTransaction.Contains(intTransId))
                            {
                                lTransaction.Add(intTransId);
                            }
                            objRSControl.MoveNext();
                        }
                        objRSControl = null;
                        //List<string> lCommands = new List<string>();
                        foreach (int JDTId in lTransaction)
                        {
                            //lCommands.AddRange(exploteJEInformation(JDTId));
                            exploteJEInformation(JDTId);
                        }
                        int j = 0;
                    }
                }
                else
                {
                    _Logger.Error("Could not initialize RecordSet");
                }
            }
            catch (Exception er)
            {
                _Logger.Error("", er);
                lTransaction = new List <int>();
            }
            return(lTransaction);
        }
예제 #5
0
        void Matrix_Data_Write()
        {
            SAPbobsCOM.Company   oCompany = (SAPbobsCOM.Company)SAPbouiCOM.Framework.Application.SBO_Application.Company.GetDICompany();
            SAPbobsCOM.Recordset oRset    = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            oRset.DoQuery(Query);

            if (oRset.RecordCount > 0)
            {
                for (int i = 0; i < oRset.RecordCount; i++)
                {
                    Matrix0.AddRow();
                    ((SAPbouiCOM.EditText)Matrix0.Columns.Item("Name").Cells.Item(i + 1).Specific).Value       = oRset.Fields.Item("lastName").Value.ToString();
                    ((SAPbouiCOM.EditText)Matrix0.Columns.Item("Surname").Cells.Item(i + 1).Specific).Value    = oRset.Fields.Item("firstName").Value.ToString();
                    ((SAPbouiCOM.EditText)Matrix0.Columns.Item("FatherName").Cells.Item(i + 1).Specific).Value = oRset.Fields.Item("middleName").Value.ToString();
                    oRset.MoveNext();
                }
            }
        }
예제 #6
0
        public static System.Data.DataTable getDataTable(string sql, string CallerRef)
        {
            System.Data.DataTable dtOut = new System.Data.DataTable();

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                SAPbobsCOM.Recordset rs = (SAPbobsCOM.Recordset)factory.Create <Recordset>(BoObjectTypes.BoRecordset);

                try
                {
                    rs.DoQuery(sql);
                    if (!rs.EoF)
                    {
                        for (int i = 0; i < rs.Fields.Count; i++)
                        {
                            dtOut.Columns.Add(rs.Fields.Item(i).Description);
                        }
                    }

                    while (!rs.EoF)
                    {
                        DataRow nr = dtOut.NewRow();
                        for (int i = 0; i < rs.Fields.Count; i++)
                        {
                            nr[i] = rs.Fields.Item(i).Value;
                        }
                        dtOut.Rows.Add(nr);
                        rs.MoveNext();
                    }
                }
                catch (Exception ex)
                {
                    dtOut = new DataTable();
                    dtOut.Columns.Add("Error");
                    dtOut.Rows.Add(ex.Message);
                }
                finally
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(rs);
                    rs = null;
                }
            }
            return(dtOut);
        }
예제 #7
0
        public IList <T> GetObjectsList <T>(string pStrWhereFieldName, string pStrWhereFieldValue, string pStrTableName) where T : Table
        {
            SAPbobsCOM.Recordset        lObjRecordSet     = null;
            Dictionary <string, string> lLstStrParameters = null;
            IList <T> lLstResult = new List <T>();
            string    lStrQuery  = "";

            try
            {
                lObjRecordSet = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                lLstStrParameters = new Dictionary <string, string>();
                lLstStrParameters.Add("WhereFieldName", pStrWhereFieldName);
                lLstStrParameters.Add("WhereFieldValue", pStrWhereFieldValue);
                lLstStrParameters.Add("TableName", pStrTableName);

                lStrQuery = this.GetSQL("GetObjectTemplate").Inject(lLstStrParameters);
                lObjRecordSet.DoQuery(lStrQuery);

                if (lObjRecordSet.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordSet.RecordCount; i++)
                    {
                        lLstResult.Add(lObjRecordSet.GetTableObject <T>());
                        lObjRecordSet.MoveNext();
                    }

                    return(lLstResult);
                }

                return(null);
            }
            catch (Exception lObjException)
            {
                throw new QueryException(lObjException.Message, lObjException);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordSet);
            }
        }
예제 #8
0
        public IList <string> GetWareHousePather(string pStrWareHouse)
        {
            SAPbobsCOM.Recordset lObjRecordset       = null;
            IList <string>       lStrWareHousePhater = new List <string>();

            try
            {
                TicketDAO mObjTicketDAO = new TicketDAO();
                Dictionary <string, string> lLstStrParameters = new Dictionary <string, string>();
                lLstStrParameters.Add("WareHouse", pStrWareHouse);
                string lStrQuery = this.GetSQL("GetWareHousePather").Inject(lLstStrParameters);
                //this.UIAPIRawForm.DataSources.DataTables.Item("RESULT").ExecuteQuery(lStrQuery);

                lObjRecordset = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                lObjRecordset.DoQuery(lStrQuery);

                if (lObjRecordset.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordset.RecordCount; i++)
                    {
                        lStrWareHousePhater.Add(lObjRecordset.Fields.Item("WhsCode").Value.ToString());

                        lObjRecordset.MoveNext();
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.WriteError(string.Format("[GetWareHousePather]: {0} ", ex.Message));
                LogService.WriteError(ex);
                UIApplication.ShowError(string.Format("[GetWareHousePather]: {0}", ex.Message));
                // UIApplication.ShowMessageBox(string.Format("InitDataSourcesException: {0}", ex.Message));
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordset);
            }

            return(lStrWareHousePhater);
        }
예제 #9
0
        private void FillAndCompareCompanies(SAPbobsCOM.Recordset oRecordSet)
        {
            cblCompanias.Items.Clear();
            while (!oRecordSet.EoF)
            {
                cblCompanias.Items.Add(oRecordSet.Fields.Item(0).Value);
                oRecordSet.MoveNext();
            }

            int i;

            string[] separador = new string[] { ";" };
            string[] lista     = SBO_VID_Currency.Properties.Settings.Default.Companies.Split(separador, StringSplitOptions.RemoveEmptyEntries);
            foreach (String s in lista)
            {
                i = cblCompanias.Items.IndexOf(s);
                if (i > -1)
                {
                    cblCompanias.SetItemChecked(i, true);
                }
            }
        }
예제 #10
0
        public System.Data.DataTable getDataTable(string sql, string CallerRef)
        {
            System.Data.DataTable dtOut = new System.Data.DataTable();
            SAPbobsCOM.Recordset  rs    = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

            try
            {
                rs.DoQuery(sql);
                if (!rs.EoF)
                {
                    for (int i = 0; i < rs.Fields.Count; i++)
                    {
                        dtOut.Columns.Add(rs.Fields.Item(i).Description);
                    }
                }

                while (!rs.EoF)
                {
                    DataRow nr = dtOut.NewRow();
                    for (int i = 0; i < rs.Fields.Count; i++)
                    {
                        nr[i] = rs.Fields.Item(i).Value;
                    }
                    dtOut.Rows.Add(nr);
                    rs.MoveNext();
                }
            }
            catch (Exception ex)
            {
                oApplication.StatusBar.SetText("Failed in Exec Query on " + CallerRef + " : " + ex.Message);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(rs);
                rs = null;
            }
            return(dtOut);
        }
예제 #11
0
        public static string CheckIfValidOrNotAllLine(SAPbobsCOM.Recordset rsConfigData, string documentType)
        {
            try
            {
                string controlName = rsConfigData.Fields.Item("U_ControlName").Value.ToString();
                string controlType = rsConfigData.Fields.Item("U_ControlType").Value.ToString();
                string accessMatrixKey = rsConfigData.Fields.Item("U_AccessMatrixKey").Value.ToString();
                string itemId = rsConfigData.Fields.Item("U_ItemId").Value.ToString();
                string colId = rsConfigData.Fields.Item("U_ColumnId").Value.ToString();
                string relatedItemId = rsConfigData.Fields.Item("U_RelatedItem").Value.ToString();
                string relatedColId = rsConfigData.Fields.Item("U_RelatedColumn").Value.ToString();
                string relatedItemId2 = rsConfigData.Fields.Item("U_RelatedItem2").Value.ToString();
                string relatedColId2 = rsConfigData.Fields.Item("U_RelatedColumn2").Value.ToString();
                string result = "Invalid " + controlName + " at line : ";
                bool   isValid = true, isValidAll = true;

                SAPbobsCOM.Recordset rs = null;

                if (controlName == "Business Partners")
                {
                    rs = GetBusinessPartnersByUser();
                }
                else if (controlName.Contains("Dimension"))
                {
                    string branch     = "";
                    bool   isBranchId = false;

                    dynamic BranchControl = AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId2).Specific;

                    if (BranchControl is SAPbouiCOM.ComboBox)
                    {
                        branch     = ((SAPbouiCOM.ComboBox)AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId2).Specific).Value;
                        isBranchId = true;
                    }
                    else //if(BranchControl is SAPbouiCOM.EditText)
                    {
                        branch     = ((SAPbouiCOM.EditText)AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId2).Specific).Value;
                        isBranchId = false;
                    }

                    rs = GetDimensionsByBranch(controlName, branch, isBranchId);
                }
                else if (controlName == "Project")
                {
                    rs = GetProjectsByUser();
                }
                else if (controlName == "G/L Account")
                {
                    rs = GetAccountsByUser();
                }

                SAPbouiCOM.Matrix oMatrix = (SAPbouiCOM.Matrix)AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId).Specific;
                int RowCount = oMatrix.RowCount;

                for (int CurrentRow = 1; CurrentRow < RowCount; CurrentRow++)
                {
                    string input = ((SAPbouiCOM.EditText)(oMatrix.Columns.Item(relatedColId).Cells.Item(CurrentRow).Specific)).Value;
                    rs.MoveFirst();
                    if (input != "")
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                isValid = true;
                                break;
                            }
                            else
                            {
                                isValid = false;
                            }
                        }
                        if (!isValid && rs.EoF)
                        {
                            isValidAll = false;
                            result    += CurrentRow.ToString() + ", ";
                        }
                    }
                }
                if (!isValidAll)
                {
                    result = result.Substring(0, result.Length - 2) + ".";
                    return(result);
                }
                return("");
            }
            catch (Exception ex)
            {
                AddOnUtilities.MsgBoxWrapper(ex.Message + " " + ex.StackTrace);
                return(ex.Message + " " + ex.StackTrace);
            }
        }
        public void RetornoNotaFiscal(SAPbobsCOM.Company oCompany)
        {
            try
            {
                if (oCompany.Connected)
                {
                    OrdersDAL orders = new OrdersDAL(oCompany);

                    SAPbobsCOM.Recordset recordSet = (Recordset)oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

                    recordSet = orders.RecuperarNumeroNF();

                    if (recordSet != null && recordSet.RecordCount > 0)
                    {
                        for (int i = 0; i < recordSet.RecordCount; i++)
                        {
                            Repositorio repositorio = new Repositorio();
                            Invoice     invoice     = new Invoice();

                            invoice.InvoicedIssueDate = String.Concat(recordSet.Fields.Item("invoiceDate").Value.ToString());
                            //invoice.InvoicedIssueDate = String.Concat(recordSet.Fields.Item("invoiceDate").Value.ToString("yyyy-MM-dd HH:mm:ss").Replace(" ","T"), "Z");
                            invoice.InvoicedNumber = recordSet.Fields.Item("invoiceNumber").Value.ToString();
                            invoice.InvoicedKey    = recordSet.Fields.Item("nfeKey").Value.ToString();
                            invoice.OrderStatus    = "INVOICED";
                            invoice.InvoicedLine   = 0;
                            string externalId              = recordSet.Fields.Item("externalId").Value.ToString();
                            string idOrderIntegraCommerce  = recordSet.Fields.Item("idOrderIntegraCommerce").Value.ToString();
                            string idOrderIntegraCommerce2 = recordSet.Fields.Item("idOrderIntegraCommerce2").Value.ToString();
                            string docSAP = recordSet.Fields.Item("docSAP").Value.ToString();
                            string docNPV = recordSet.Fields.Item("docNPIntegraCommerce").Value.ToString();

                            //invoice.invoiceValue = recordSet.Fields.Item("totalNF").Value.ToString().Replace(",","");
                            //invoice.courier = recordSet.Fields.Item("shippingMethod").Value.ToString();

                            int updatePedidoNum = 0;

                            if (!string.IsNullOrEmpty(idOrderIntegraCommerce))
                            {
                                invoice.IdOrder = idOrderIntegraCommerce;
                            }
                            else if (!string.IsNullOrEmpty(idOrderIntegraCommerce2))
                            {
                                invoice.IdOrder = idOrderIntegraCommerce2;
                            }

                            Task <HttpResponseMessage> responseOrder = repositorio.BuscarPedido(idOrderIntegraCommerce);

                            if (responseOrder.Result.IsSuccessStatusCode)
                            {
                                var jsonOrder = responseOrder.Result.Content.ReadAsStringAsync().Result;

                                var _order = JsonConvert.DeserializeObject <OrderIntegraCommerce>(jsonOrder);


                                //Para validar para enviar só se o pedido não estiver cancelado
                                if (!_order.OrderStatus.Equals("CANCELED"))
                                {
                                }

                                if (!string.IsNullOrEmpty(invoice.IdOrder))
                                {
                                    Task <HttpResponseMessage> response = repositorio.RetornoNotaFiscal(invoice);

                                    if (response.Result.IsSuccessStatusCode)
                                    {
                                        //Atualizando campo de usuário U_EnvioNFVTEX
                                        updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));

                                        if (updatePedidoNum == 0)
                                        {
                                            this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, docSAP, EnumStatusIntegracao.Sucesso, "Número NF " + invoice.InvoicedNumber + " enviado para IntegraCommerce com sucesso.");
                                            this.log.WriteLogRetornoNF("Número NF para o Pedido de Venda " + docSAP + " enviado para IntegraCommerce com sucesso.");
                                        }
                                        else
                                        {
                                            this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, docSAP, EnumStatusIntegracao.Erro, "Número NF " + invoice.InvoicedNumber + " retornado porém não foi possivél atualizar campo de usuário (U_EnvioNFIC) do Pedido de Venda");
                                            this.log.WriteLogRetornoNF("Falha ao atualizar Pedido de Venda " + docSAP);
                                        }
                                    }
                                    else
                                    {
                                        var responseNFJson = response.Result.Content.ReadAsStringAsync().Result;
                                        var responseBody   = JsonConvert.DeserializeObject <RetNFResponse>(responseNFJson);

                                        var responseMessage = string.Empty;

                                        foreach (Error err in responseBody.Errors)
                                        {
                                            if (!String.IsNullOrEmpty(err.Message))
                                            {
                                                responseMessage = err.Message;
                                            }
                                            else
                                            {
                                                responseMessage = response.Result.ReasonPhrase;
                                            }
                                        }

                                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, externalId, EnumStatusIntegracao.Erro, responseMessage);
                                        this.log.WriteLogRetornoNF("Falha ao retornar número da Nota Fiscal " + externalId + " para IntegraCommerce");

                                        //Atualizando campo de usuário U_EnvioNFVTEX
                                        updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));

                                        if (updatePedidoNum != 0)
                                        {
                                            //this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, docSAP, EnumStatusIntegracao.Erro, "Número NF " + invoice.InvoicedNumber + " retornado porém não foi possivél atualizar campo de usuário (U_EnvioNFIntegraC) do Pedido de Venda");
                                            this.log.WriteLogRetornoNF("Falha ao atualizar Pedido de Venda " + docSAP);
                                        }
                                    }
                                }
                                else
                                {
                                    this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, externalId, EnumStatusIntegracao.Erro, "Id do Pedido IntegraCommerce (NumAtCard e U_NumPedEXT) do Pedido de Venda " + docNPV + " em branco.");
                                    this.log.WriteLogRetornoNF("Falha ao retornar número da Nota Fiscal " + externalId + " para a Vtex - Id do Pedido IntegraCommerce (NumAtCard) do Pedido de Venda " + docNPV + " em branco.");

                                    //Atualizando campo de usuário U_EnvioNFVTEX
                                    updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));

                                    if (updatePedidoNum != 0)
                                    {
                                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, invoice.IdOrder, docSAP, EnumStatusIntegracao.Erro, "Número NF " + invoice.InvoicedNumber + " retornado porém não foi possivél atualizar campo de usuário (U_EnvioNFIntegraC) do Pedido de Venda");
                                        this.log.WriteLogRetornoNF("Falha ao atualizar Pedido de Venda " + docSAP);
                                    }
                                }
                            }

                            recordSet.MoveNext();
                        }
                    }

                    if (recordSet != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(recordSet);
                    }
                }
            }
            catch (Exception e)
            {
                this.log.WriteLogRetornoNF("Exception RetornoNotaFiscal " + e.Message);
                //throw;
            }
        }
예제 #13
0
        private Documents GetLines(Documents pObjSaleOrder, string pStrRequestId, int pIntMobilizationTypeId)
        {
            SAPbobsCOM.Recordset lObjRecordSet = null;
            string lStrInsurenceItemCode       = "";
            string lStrQuery  = "";
            string lStrResult = mObjQueryManager.GetValue("U_ParentProductId", "U_RequestId", pStrRequestId, "[@UG_PE_WS_PRRE]");

            LogService.WriteInfo("[SaleOrder: TipoGanado " + lStrResult + "]");
            if (lStrResult == "105" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_EQUINO", "[@UG_CONFIG]");
                string lStrItem = string.IsNullOrEmpty(lStrInsurenceItemCode.ToString()) ? "Item no encontrado" : lStrInsurenceItemCode.ToString();
                LogService.WriteInfo("[SaleOrder: ItemCode " + lStrItem + "]");

                double lDouInsurencePrice = GetInsurencePrice(lStrInsurenceItemCode.ToString());
                if (lDouInsurencePrice <= 0)
                {
                    LogService.WriteInfo("[SaleOrder: Precio no encontrado");
                }
                LogService.WriteInfo("[SaleOrder: Precio " + lDouInsurencePrice + "]");
            }
            if (lStrResult == "1" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_BOVINO", "[@UG_CONFIG]");
                string lStrItem = string.IsNullOrEmpty(lStrInsurenceItemCode.ToString()) ? "Item no encontrado" : lStrInsurenceItemCode.ToString();
                LogService.WriteInfo("[SaleOrder: ItemCode " + lStrItem + "]");

                double lDouInsurencePrice = GetInsurencePrice(lStrInsurenceItemCode.ToString());
                if (lDouInsurencePrice <= 0)
                {
                    LogService.WriteInfo("[SaleOrder: Precio no encontrado");
                }
                LogService.WriteInfo("[SaleOrder: Precio " + lDouInsurencePrice + "]");
            }



            try {
                lObjRecordSet = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                Dictionary <string, string> lLstStrParameters = new Dictionary <string, string>();
                lLstStrParameters.Add("RequestId", pStrRequestId);
                lLstStrParameters.Add("MobilizationTypeId", pIntMobilizationTypeId.ToString());
                lStrQuery = this.GetSQL("GetItemAndPriceByProductRequests").Inject(lLstStrParameters);

                lObjRecordSet.DoQuery(lStrQuery);

                for (int i = 0; i < pObjSaleOrder.Lines.Count; i++)
                {
                    pObjSaleOrder.Lines.SetCurrentLine(i);
                    pObjSaleOrder.Lines.Delete();
                }


                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_BOVINO", "[@UG_CONFIG]");
                int lIntLintCountRows = mObjQueryManager.Count("U_RequestId", pStrRequestId, "[@UG_PE_WS_PRRE]");

                if (lObjRecordSet.RecordCount > 0 && lObjRecordSet.RecordCount == lIntLintCountRows)
                {
                    for (int i = 0; i < lObjRecordSet.RecordCount; i++)
                    {
                        //pObjSaleOrder.Lines.SetCurrentLine(i);
                        pObjSaleOrder.Lines.WarehouseCode = "PEHE";
                        pObjSaleOrder.Lines.ItemCode      = lObjRecordSet.Fields.Item("U_ItemCode").Value.ToString();
                        pObjSaleOrder.Lines.Quantity      = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                        pObjSaleOrder.Lines.Price         = Convert.ToDouble(lObjRecordSet.Fields.Item("Price").Value.ToString());
                        pObjSaleOrder.Lines.ItemDetails   = lObjRecordSet.Fields.Item("U_Description").Value.ToString();
                        pObjSaleOrder.Lines.CostingCode   = "OG_PERMI";
                        //pObjSaleOrder.Update();
                        pObjSaleOrder.Lines.Add();


                        string lStrInsureCU    = string.Empty;
                        string lStrInsureTrans = string.Empty;

                        lStrInsureCU    = lObjRecordSet.Fields.Item("U_InsureCU").Value.ToString();
                        lStrInsureTrans = lObjRecordSet.Fields.Item("U_InsureTrans").Value.ToString();

                        if (!string.IsNullOrEmpty(lStrInsureCU))
                        {
                            pObjSaleOrder.Lines.WarehouseCode = "PEHE";
                            pObjSaleOrder.Lines.ItemCode      = lStrInsureCU;
                            double lDblQuantity = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                            double lDblPrice    = GetInsurencePrice(lStrInsureCU.ToString());
                            pObjSaleOrder.Lines.Quantity    = 1;
                            pObjSaleOrder.Lines.Price       = Math.Ceiling(lDblPrice * lDblQuantity);
                            pObjSaleOrder.Lines.CostingCode = "OG_PERMI";
                            pObjSaleOrder.Lines.Add();
                        }

                        if (!string.IsNullOrEmpty(lStrInsureTrans))
                        {
                            pObjSaleOrder.Lines.WarehouseCode = "PEHE";
                            pObjSaleOrder.Lines.ItemCode      = lStrInsureTrans;
                            double lDblQuantity = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                            double lDblPrice    = GetInsurencePrice(lStrInsureTrans.ToString());
                            pObjSaleOrder.Lines.Quantity    = 1;
                            pObjSaleOrder.Lines.Price       = Math.Ceiling(lDblPrice * lDblQuantity);
                            pObjSaleOrder.Lines.CostingCode = "OG_PERMI";
                            pObjSaleOrder.Lines.Add();
                        }
                        lObjRecordSet.MoveNext();
                    }
                    //double lDblTotal = pObjSaleOrder.DocTotal;
                }
                else
                {
                    LogService.WriteError("No fue posible encontrar los articulos favor de revisar la tabla de relación con SAP IdRequest:" + pStrRequestId);
                }
            }
            catch (Exception ex) {
                LogService.WriteInfo(ex.Message + " " + ex.StackTrace);
            }
            finally {
                MemoryUtility.ReleaseComObject(lObjRecordSet);
            }

            return(pObjSaleOrder);
        }
예제 #14
0
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            //SAPbouiCOM.ComboBox oComboBox;
            SAPbouiCOM.Column oColumn;

            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            try
            {
                oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                //Lista    := New list<string>;

                FSBOf.LoadForm(xmlPath, "VID_GLibro.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = false;
                oForm.SupportedModes = -1;       // afm_All

                oForm.EnableMenu("1281", false); //Actualizar
                oForm.EnableMenu("1282", false); //Crear

                oForm.DataSources.UserDataSources.Add("TipoLibro", BoDataType.dt_SHORT_TEXT);
                oComboBox = (ComboBox)(oForm.Items.Item("TipoLibro").Specific);
                oComboBox.DataBind.SetBound(true, "", "TipoLibro");
                oComboBox.ValidValues.Add("V", "Venta");
                oComboBox.ValidValues.Add("C", "Compra");
                oComboBox.ValidValues.Add("B", "Boletas");
                oComboBox.ValidValues.Add("G", "Guias");
                oComboBox.Select("V", BoSearchKey.psk_ByValue);

                oForm.DataSources.UserDataSources.Add("Desde", BoDataType.dt_DATE, 10);
                oEditText = (EditText)(oForm.Items.Item("Desde").Specific);
                oEditText.DataBind.SetBound(true, "", "Desde");
                oEditText.Value = DateTime.Now.ToString("yyyyMM") + "01";

                oForm.DataSources.UserDataSources.Add("Hasta", BoDataType.dt_DATE, 10);
                oEditText = (EditText)(oForm.Items.Item("Hasta").Specific);
                oEditText.DataBind.SetBound(true, "", "Hasta");
                oEditText.Value = DateTime.Now.ToString("yyyyMMdd");

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select ISNULL(U_MultiSoc,'N') MultiSoc from [@VID_FEPARAM]";
                }
                else
                {
                    s = @"select IFNULL(""U_MultiSoc"",'N') ""MultiSoc"" from ""@VID_FEPARAM"" ";
                }
                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    if (((System.String)oRecordSet.Fields.Item("MultiSoc").Value) == "Y")
                    {
                        bMultiSoc = true;
                    }
                }

                if (bMultiSoc)
                {
                    oForm.Items.Item("LInstituto").Visible = true;
                    oForm.Items.Item("Instituto").Visible  = true;
                    oComboBox = (ComboBox)(oForm.Items.Item("Instituto").Specific);
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select DocEntry, U_Sociedad 'Sociedad' from [@VID_FEMULTISOC] where isnull(U_Habilitada,'N') = 'Y'";
                    }
                    else
                    {
                        s = @"select ""DocEntry"", ""U_Sociedad"" ""Sociedad"" from ""@VID_FEMULTISOC"" where IFNULL(""U_Habilitada"",'N') = 'Y' ";
                    }
                    oRecordSet.DoQuery(s);
                    while (!oRecordSet.EoF)
                    {
                        oComboBox.ValidValues.Add(((System.Int32)oRecordSet.Fields.Item("DocEntry").Value).ToString(), ((System.String)oRecordSet.Fields.Item("Sociedad").Value).Trim());
                        oRecordSet.MoveNext();
                    }
                }
                else
                {
                    oForm.Items.Item("LInstituto").Visible = false;
                    oForm.Items.Item("Instituto").Visible  = false;
                }
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            oForm.Freeze(false);
            return(Result);
        }//fin InitForm
        public void IniciarIntegracaoEstoque(SAPbobsCOM.Company oCompany)
        {
            string numItemTeste = string.Empty;

            try
            {
                Repositorio repositorio = new Repositorio();

                this.log.WriteLogEstoque("Inicio do Processo de Integração de Estoque");

                WarehouseDAL whsDAL = new WarehouseDAL();

                SAPbobsCOM.Recordset recordset = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                recordset = whsDAL.RecuperarSaldoEstoqueSAP(oCompany);



                if (recordset != null && recordset.RecordCount > 0)
                {
                    for (int i = 0; i < recordset.RecordCount; i++)
                    {
                        try
                        {
                            string _itemCode   = recordset.Fields.Item("ItemCode").Value.ToString();
                            Int16  _onHand     = System.Convert.ToInt16(recordset.Fields.Item("OnHand").Value.ToString());
                            string warehouseId = ConfigurationManager.AppSettings["warehouseId"];
                            numItemTeste = _itemCode;
                            Task <HttpResponseMessage> response = repositorio.BuscarItemPorSKU(_itemCode, oCompany);

                            if (response.Result.IsSuccessStatusCode)
                            {
                                Item item = new Item();

                                var jsonResponse = response.Result.Content.ReadAsStringAsync();

                                item = JsonConvert.DeserializeObject <Item>(jsonResponse.Result);

                                //Log.WriteLog("Item " + item.ManufacturerCode + " localizado.");

                                if (item.Status)
                                {
                                    Task <HttpResponseMessage> responseAtualizacaoEstoque = repositorio.AtualizarQuantidadeEstoque(_itemCode, _onHand);

                                    if (responseAtualizacaoEstoque.Result.IsSuccessStatusCode)
                                    {
                                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, _itemCode, _itemCode, EnumStatusIntegracao.Sucesso, "Estoque atualizado com sucesso.");
                                        this.log.WriteLogEstoque("Quantidade de estoque do Produto " + _itemCode + " para o depósito " + warehouseId + " atualizada com sucesso.");
                                    }
                                    else
                                    {
                                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, _itemCode, _itemCode, EnumStatusIntegracao.Erro, response.Result.ReasonPhrase);
                                        this.log.WriteLogEstoque("Não foi possível atualizar a quantidade de estoque para o produto " + _itemCode + ". Retorno API IntegraCommerce: " + response.Result.ReasonPhrase);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }

                        recordset.MoveNext();
                    }
                }

                if (recordset != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(recordset);
                }
            }
            catch (Exception e)
            {
                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, "", "", EnumStatusIntegracao.Erro, e.Message + numItemTeste);
                this.log.WriteLogEstoque("Exception IniciarProcessoEstoque " + e.Message);
                throw;
            }
        }
예제 #16
0
        private bool UDO_Add_Data()
            
        {
            SAPbobsCOM.GeneralService oGeneralService = null;
            SAPbobsCOM.GeneralData oGeneralData = null;
            SAPbobsCOM.GeneralDataCollection oChildren = null;
            SAPbobsCOM.GeneralData oChild = null;
            SAPbobsCOM.CompanyService oCompanyService = (SAPbobsCOM.CompanyService)B1Connections.diCompany.GetCompanyService();
            
            oRS = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            oRS1 = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            StringBuilder pQuery = new StringBuilder();
            string sQry = string.Empty;

            #region  DataSetting_쿼리문
            pQuery.Clear();
            pQuery.AppendLine("   SELECT                                                                                    ");
            pQuery.AppendLine("      ''				AS EXAMCD                                                               ");
            pQuery.AppendLine("     ,T0.U_EMPNO		AS EMPNO                                                                ");
            pQuery.AppendLine("     ,T0.U_EMPNM		AS EMPNM                                                                ");
            pQuery.AppendLine("     ,''			    AS DTCD                                                                 ");
            pQuery.AppendLine("     ,''			    AS TEAMCD                                                               ");
            pQuery.AppendLine("     ,T1.U_DEPTCD 	AS DEPTCD                                                               ");
            pQuery.AppendLine("     ,T0.U_JIKGBCD	AS JIKGBCD                                                              ");
            pQuery.AppendLine("     ,T0.U_JIKCHCD	AS JIKCHKCD                                                             ");
            pQuery.AppendLine("     ,0 			    AS PASSYN                                                               ");
            pQuery.AppendLine("     ,0				AS CARDPSYN                                                             ");
            pQuery.AppendLine("     ,0 			    AS USEYN                                                                ");
            pQuery.AppendLine("     ,NULL			AS LASTSBF                                                              ");
            pQuery.AppendLine("     ,0				AS LASTGBF                                                              ");
            pQuery.AppendLine("     ,NULL			AS LASTSAF                                                              ");
            pQuery.AppendLine("     ,0				AS LASTGAF                                                              ");
            pQuery.AppendLine("   FROM [@KIS_HR0120M] T0                                                                    ");
            pQuery.AppendLine("   INNER JOIN (                                                                              ");
            pQuery.AppendLine("   			SELECT                                                                          ");
            pQuery.AppendLine("   				   A.Code                                                                   ");
            pQuery.AppendLine("   				 , CASE WHEN B.CNT = 1 THEN                                                 ");
            pQuery.AppendLine("   							CASE WHEN A.U_IDEPTYN = 'Y' THEN MAX(A.U_DEPTCD) ELSE NULL END  ");
            pQuery.AppendLine("   						ELSE                                                                ");
            pQuery.AppendLine("   							MAX(A.U_DEPTCD)                                                 ");
            pQuery.AppendLine("   				   END AS U_DEPTCD                                                          ");
            pQuery.AppendLine("   			FROM [@KIS_HR01202] A                                                           ");
            pQuery.AppendLine("   			INNER JOIN (                                                                    ");
            pQuery.AppendLine("   							SELECT                                                          ");
            pQuery.AppendLine("   								 COUNT(Code)	AS CNT                                      ");
            pQuery.AppendLine("   								,Code                                                       ");
            pQuery.AppendLine("   								,U_IDEPTYN								                    ");
            pQuery.AppendLine("   							FROM [@KIS_HR01202]                                             ");
            pQuery.AppendLine("   							GROUP BY Code,U_IDEPTYN                                         ");
            pQuery.AppendLine("   			) B ON A.Code = B.Code                                                          ");
            pQuery.AppendLine("   			WHERE                                                                           ");
            pQuery.AppendLine("   			NOT EXISTS(                                                                     ");
            pQuery.AppendLine("   						SELECT                                                              ");
            pQuery.AppendLine("   							 COUNT(Code)	AS CNT                                          ");
            pQuery.AppendLine("   							,Code                                                           ");
            pQuery.AppendLine("   							,U_IDEPTYN								                        ");
            pQuery.AppendLine("   						FROM [@KIS_HR01202]                                                 ");
            pQuery.AppendLine("   						WHERE (B.CNT = 1 AND B.U_IDEPTYN = 'N')	                            ");
            pQuery.AppendLine("   						GROUP BY Code,U_IDEPTYN                                             ");
            pQuery.AppendLine("   					 )                                                                      ");
            pQuery.AppendLine("   			GROUP BY A.Code  , B.CNT , A.U_IDEPTYN                                          ");
            pQuery.AppendLine("   ) T1 ON T0.Code = T1.Code                                                                 ");
            pQuery.AppendLine("   WHERE T1.U_DEPTCD IS NOT NULL                                                             ");

            #endregion

            oRS.DoQuery(pQuery.ToString());

            SAPbouiCOM.ProgressBar ProgressBar01 = B1Connections.theAppl.StatusBar.CreateProgressBar(String.Format("고과마스터 생성중...(0/{0})", oRS.RecordCount), oRS.RecordCount, false);
            KIS_COMMON.GLOBAL.PrograssBarExcute = true;

            try
            {

                for (int j = 0; j < oRS.RecordCount; j++)
                {
                    oGeneralService = oCompanyService.GetGeneralService("KIS_HR0020_HRD");
                    oGeneralData = (SAPbobsCOM.GeneralData)oGeneralService.GetDataInterface(SAPbobsCOM.GeneralServiceDataInterfaces.gsGeneralData);      
                    
                    if (KIS_COMMON.GLOBAL.PrograssBarExcute == true)
                    {
                        ProgressBar01.Value++;
                        ProgressBar01.Text = String.Format("고과마스터 생성중 ... ({0}/{1})", ProgressBar01.Value, oRS.RecordCount);
                        System.Windows.Forms.Application.DoEvents();
                    }

                    #region  DataSetting_헤더
                    string H_Code = FN.GetMaxCode("@KIS_HR0020M_HRD"); ;
                    string H_Name = H_Code;
                    string H_EMPNO = oRS.Fields.Item("EMPNO").Value.ToString();//사번
                    string H_EMPNM = oRS.Fields.Item("EMPNM").Value.ToString();//사원명
                    string H_DTCD = oRS.Fields.Item("DTCD").Value.ToString();//구분코드
                    string H_TEAMCD = oRS.Fields.Item("TEAMCD").Value.ToString();//팀코드
                    string H_DEPTCD = oRS.Fields.Item("DEPTCD").Value.ToString();//부서코드
                    string H_JIKGBCD = oRS.Fields.Item("JIKGBCD").Value.ToString();//직급코드
                    string H_JIKCHKCD = oRS.Fields.Item("JIKCHKCD").Value.ToString();//직책코드
                    string H_PASSYN = oRS.Fields.Item("PASSYN").Value.ToString();//본인작성사용여부
                    string H_CARDPSYN = oRS.Fields.Item("CARDPSYN").Value.ToString();//인재육성카드적성여부
                    string H_USEYN = oRS.Fields.Item("USEYN").Value.ToString();//사용여부
                    string H_LASTSBF = oRS.Fields.Item("LASTSBF").Value.ToString();//항목최종점수_수정전
                    string H_LASTGBF = oRS.Fields.Item("LASTGBF").Value.ToString();//항목최종등급_수정전
                    string H_LASTSAF = oRS.Fields.Item("LASTSAF").Value.ToString();//항목최종점수_수정후
                    string H_LASTGAF = oRS.Fields.Item("LASTGAF").Value.ToString();//항목최종등금_수정후
                    #endregion

                    oGeneralData.SetProperty("Code", H_Code);
                    oGeneralData.SetProperty("Name", H_Name);
                    oGeneralData.SetProperty("U_EXAMCD", EXAMCD);
                    oGeneralData.SetProperty("U_EMPNO", H_EMPNO);
                    oGeneralData.SetProperty("U_EMPNM", H_EMPNM);
                    oGeneralData.SetProperty("U_DTCD", H_DTCD);
                    oGeneralData.SetProperty("U_DEPTCD", H_DEPTCD);
                    oGeneralData.SetProperty("U_TEAMCD", H_TEAMCD);
                    oGeneralData.SetProperty("U_JIKGBCD", H_JIKGBCD);
                    oGeneralData.SetProperty("U_JIKCHKCD", H_JIKCHKCD);
                    oGeneralData.SetProperty("U_PASSYN", H_PASSYN);
                    oGeneralData.SetProperty("U_CARDPSYN", H_CARDPSYN);
                    oGeneralData.SetProperty("U_USEYN", H_USEYN);
                    oGeneralData.SetProperty("U_LASTSBF", H_LASTSBF);
                    oGeneralData.SetProperty("U_LASTGBF", H_LASTGBF);
                    oGeneralData.SetProperty("U_LASTSAF", H_LASTSAF);
                    oGeneralData.SetProperty("U_LASTGAF", H_LASTGAF);
                    oGeneralData.SetProperty("U_STATUS", "Y");

                    oChildren = oGeneralData.Child("KIS_HR00202_HRD");

                    #region  DataSetting_라인쿼리문
                    pQuery.Clear();
                    pQuery.AppendLine("  SELECT                                                             ");
                    pQuery.AppendLine("     A.U_RMK2		AS DTCD			/*객관식 주관식 구분 코드*/     ");
                    pQuery.AppendLine("    ,A.U_RMK3		AS DTNM			/*객관식 주관식 구분 내용*/     ");
                    pQuery.AppendLine("    ,A.U_SMLCD		AS ABILCD		/*항목*/                        ");
                    pQuery.AppendLine("    ,A.U_SMLNM		AS ABILNM		/*항목내용*/                    ");
                    pQuery.AppendLine("    ,B.U_SMLCD		AS COMPOCD		/*세부항목*/                    ");
                    pQuery.AppendLine("    ,B.U_SMLNM		AS COMPONM		/*세부항목내용*/                ");
                    pQuery.AppendLine("    ,NULL			AS SELVAL		/*결과값*/                      ");
                    pQuery.AppendLine("    ,NULL			AS SELVALNM		/*결과값내용*/                  ");
                    pQuery.AppendLine("    ,NULL			AS CONTENT1		/*피고과자의견*/                ");
                    pQuery.AppendLine("    ,NULL			AS CONTENT2		/*고과자의견*/                  ");
                    pQuery.AppendLine("   FROM [@KIS_AD00201] A                                             ");
                    pQuery.AppendLine("   LEFT OUTER JOIN  [@KIS_AD00201] B ON A.U_RMK1 = B.Code            ");
                    pQuery.AppendLine("   WHERE  A.CODE = 'HR07'                                            ");
                    #endregion

                    oRS1.DoQuery(pQuery.ToString());

                    for (int jLooper = 0; jLooper < oRS1.RecordCount; jLooper++)
                    {
                        #region  DataSetting_라인
                        string L_DTCD = oRS1.Fields.Item("DTCD").Value.ToString();//객관식 주관식 구분 코드
                        string L_DTNM = oRS1.Fields.Item("DTNM").Value.ToString();//객관식 주관식 구분 내용
                        string L_ABILCD = oRS1.Fields.Item("ABILCD").Value.ToString();//항목
                        string L_ABILNM = oRS1.Fields.Item("ABILNM").Value.ToString();//항목내용
                        string L_COMPOCD = oRS1.Fields.Item("COMPOCD").Value.ToString();//세부항목
                        string L_COMPONM = oRS1.Fields.Item("COMPONM").Value.ToString();//세부항목내용
                        string L_SELVAL = oRS1.Fields.Item("SELVAL").Value.ToString();//결과값
                        string L_SELVALNM = oRS1.Fields.Item("SELVALNM").Value.ToString();//결과값내용
                        string L_CONTENT1 = oRS1.Fields.Item("CONTENT1").Value.ToString();//피고과자의견
                        string L_CONTENT2 = oRS1.Fields.Item("CONTENT2").Value.ToString();//고과자의견
                        #endregion

                        oChild = oChildren.Add();
                        oChild.SetProperty("U_LINENUM", jLooper + 1);
                        oChild.SetProperty("U_DTCD", L_DTCD);
                        oChild.SetProperty("U_DTNM", L_DTNM);
                        oChild.SetProperty("U_ABILCD", L_ABILCD);
                        oChild.SetProperty("U_ABILNM", L_ABILNM);
                        oChild.SetProperty("U_COMPOCD", L_COMPOCD);
                        oChild.SetProperty("U_COMPONM", L_COMPONM);
                        oChild.SetProperty("U_SELVAL", L_SELVAL);
                        oChild.SetProperty("U_SELVALNM", L_SELVALNM);
                        oChild.SetProperty("U_CONTENT1", L_CONTENT1);
                        oChild.SetProperty("U_CONTENT2", L_CONTENT2);
                        oChild.SetProperty("U_EXAMCD", EXAMCD);
                        oRS1.MoveNext();
                    }

                    oRS.MoveNext();
                    oGeneralService.Add(oGeneralData);

                }

            }

            catch (Exception ex)
            {
                B1Connections.theAppl.StatusBar.SetText(ex.Message, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                return false;
            }
            finally
            {
                if (KIS_COMMON.GLOBAL.PrograssBarExcute == true)
                {
                    ProgressBar01.Stop();
                    KIS_COMMON.GLOBAL.PrograssBarExcute = false;
                }
                releaseObject(ProgressBar01);
                oCompanyService = null;
            }
            return true;
        }
예제 #17
0
        private Documents GetLines(Documents pObjSaleOrder, string pStrRequestId, int pIntMobilizationTypeId)
        {
            SAPbobsCOM.Recordset lObjRecordSet = null;
            string lStrInsurenceItemCode       = "";
            string lStrQuery  = "";
            string lStrResult = mObjQueryManager.GetValue("U_ParentProductId", "U_RequestId", pStrRequestId, "[@UG_PE_WS_PRRE]");

            LogService.WriteInfo("[SaleOrder: TipoGanado" + lStrResult + "]");
            if (lStrResult == "105" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_EQUINO", "[@UG_CONFIG]");;
            }
            if (lStrResult == "1" && pIntMobilizationTypeId == 2)
            {
                lStrInsurenceItemCode = mObjQueryManager.GetValue("U_Value", "Name", "PE_SEG_BOVINO", "[@UG_CONFIG]");;
            }
            LogService.WriteInfo("[SaleOrder: ItemCode" + lStrInsurenceItemCode.ToString() + "]");
            double lDouInsurencePrice = GetInsurencePrice(lStrInsurenceItemCode.ToString());

            LogService.WriteInfo("[SaleOrder: Precio" + lDouInsurencePrice + "]");

            try
            {
                lObjRecordSet = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                Dictionary <string, string> lLstStrParameters = new Dictionary <string, string>();
                lLstStrParameters.Add("RequestId", pStrRequestId);
                lLstStrParameters.Add("MobilizationTypeId", pIntMobilizationTypeId.ToString());
                lStrQuery = this.GetSQL("GetItemAndPriceByProductRequests").Inject(lLstStrParameters);

                lObjRecordSet.DoQuery(lStrQuery);

                if (lObjRecordSet.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordSet.RecordCount; i++)
                    {
                        pObjSaleOrder.Lines.SetCurrentLine(i);
                        pObjSaleOrder.Lines.WarehouseCode = "OFGE";
                        pObjSaleOrder.Lines.ItemCode      = lObjRecordSet.Fields.Item("U_ItemCode").Value.ToString();
                        pObjSaleOrder.Lines.Quantity      = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                        pObjSaleOrder.Lines.Price         = Convert.ToDouble(lObjRecordSet.Fields.Item("Price").Value.ToString());
                        pObjSaleOrder.Lines.CostingCode   = "OG_PERMI";
                        //pObjSaleOrder.Update();
                        pObjSaleOrder.Lines.Add();

                        if (pIntMobilizationTypeId == 2)
                        {
                            pObjSaleOrder.Lines.WarehouseCode = "OFGE";
                            pObjSaleOrder.Lines.ItemCode      = lStrInsurenceItemCode;
                            pObjSaleOrder.Lines.Quantity      = Convert.ToDouble(lObjRecordSet.Fields.Item("U_Quantity").Value.ToString());
                            pObjSaleOrder.Lines.Price         = lDouInsurencePrice;
                            pObjSaleOrder.Lines.CostingCode   = "OG_PERMI";


                            pObjSaleOrder.Lines.Add();
                        }

                        lObjRecordSet.MoveNext();
                    }
                }
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordSet);
            }

            return(pObjSaleOrder);
        }
예제 #18
0
        private void GetCostCenterList()
        {
            StringBuilder sb = new StringBuilder();
            SAPbobsCOM.Recordset oRS = null;
            string expression = string.Empty;
            System.Data.DataRow[] foundRows;
            int iRow;
            bool bModify = false;
            try
            {
                oForm.Freeze(true);
                oDB_M = oForm.DataSources.DBDataSources.Item("@KIS_FI0010M_HRD");
                oDB_1 = oForm.DataSources.DBDataSources.Item("@KIS_FI00101_HRD");

                oMatrix = (SAPbouiCOM.Matrix)oForm.Items.Item("mtx").Specific;
                //oMatrix.LoadFromDataSource();

                oMatrix.Clear();
                FN.SetMatrixIsNullOrEmptDeleteRow(ref oForm, ref oMatrix, "U_PRCCD");

                sDataTable = FN.SapDBDataSourceToSystemDataTable(oDB_1);

                oRS = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                sb.Append(" SELECT Code,Name FROM [@KIS_CO0110M]                               \r");

                if (FN.GetItemValue(ref oForm, "edtCOSTFR") != "" && FN.GetItemValue(ref oForm, "edtCOSTTO") != "")
                    sb.Append("    WHERE Code BETWEEN '" + FN.GetItemValue(ref oForm, "edtCOSTFR") + "' AND '" + FN.GetItemValue(ref oForm, "edtCOSTTO") + "' \r");

                B1Connections.theAppl.StatusBar.SetText("불러오기를 시작합니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                oRS.DoQuery(sb.ToString());

                iRow = oMatrix.VisualRowCount;
                if (!oRS.EoF)
                {
                    for (int i = 0; i < oRS.RecordCount; i++)
                    {
                        expression = "U_PRCCD = '" + oRS.Fields.Item("Code").Value.ToString() + "'";
                        foundRows = sDataTable.Select(expression);

                        if (foundRows.Length < 1)
                        {
                            if (iRow != 0)
                                oDB_1.InsertRecord(iRow-1);

                            //oDB_1.SetValue("U_LINENUM", iRow, (iRow+1).ToString());
                            oDB_1.SetValue("U_PRCCD", iRow, oRS.Fields.Item("Code").Value.ToString());
                            oDB_1.SetValue("U_PRCNM", iRow, oRS.Fields.Item("Name").Value.ToString());

                            iRow += 1;
                            bModify = true;
                        }
                        oRS.MoveNext();
                    }
                    if (bModify)
                    {
                        oMatrix.LoadFromDataSource();
                        if (oForm.Mode == BoFormMode.fm_OK_MODE)
                            oForm.Mode = BoFormMode.fm_UPDATE_MODE;
                    }
                }
                B1Connections.theAppl.StatusBar.SetText("불러오기가 완료 되었습니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning); //데이터 조회중입니다
            }
            catch (Exception ex)
            {
                oForm.Freeze(false);
                B1Connections.theAppl.StatusBar.SetText("GetCostCenterList " + ex.Message, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
            }
            finally
            {
                if (oRS != null)
                {
                    oForm.Freeze(false);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oRS);
                    oRS = null;
                }
            }
        }
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            Int32 i;
            //TFunctions Reg;
            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            try
            {
                oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                Lista = new List <string>();

                FSBOf.LoadForm(xmlPath, "VID_FEPROCED.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = true;
                oForm.SupportedModes = -1;             // afm_All

                //        VID_DelRow := true;
                //        VID_DelRowOK := true;

                //oForm.DataBrowser.BrowseBy := "Code";
                oDBDSH = oForm.DataSources.DBDataSources.Item("@VID_FEPROCED");

                // Ok Ad  Fnd Vw Rq Sec
                Lista.Add("mtx      , f,  t,  f,  f, r, 1");
                //Lista.Add('Name      , f,  t,  t,  f, r, 1');
                //Lista.Add('CardCode  , f,  t,  t,  f, r, 1');
                //FSBOf.SetAutoManaged(var oForm, Lista);

                //oCombo := ComboBox(oForm.Items.Item('TipDoc').Specific);
                //oCombo.ValidValues.Add('33', 'Factura');

                //s := '1';
                //oCombo.Select(s, BoSearchKey.psk_ByValue);

                //        AddChooseFromList();
                oMtx = (Matrix)(oForm.Items.Item("mtx").Specific);
                //        oColumn                    := SAPbouiCOM.Column(oMtx.Columns.Item('V_0'));
                //        oColumn.ChooseFromListUID  := 'CFL0';
                //        oColumn.ChooseFromListAlias:= 'Code';
                //        oMtx.AutoResizeColumns();


                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select DocEntry, ISNULL(U_TipoDoc,'') TipoDoc, ISNULL(U_ProcNomE,'') ProcNomE, ISNULL(U_ProcNomD,'') ProcNomD, ISNULL(U_ProcNomR,'') ProcNomR, ISNULL(U_ProcNomC,'') ProcNomC, ISNULL(U_ProcNomDe,'') ProcNomDe, ISNULL(U_ProcNomL,'') ProcNomL, ISNULL(U_ProcNomS,'') ProcNomS, ISNULL(U_Habili,'Y') 'Habilitada', ISNULL(U_CantLineas,0) 'CantLineas' from [@VID_FEPROCED]";
                }
                else
                {
                    s = @"select ""DocEntry"", IFNULL(""U_TipoDoc"",'') ""TipoDoc"", IFNULL(""U_ProcNomE"",'') ""ProcNomE"", IFNULL(""U_ProcNomD"",'') ""ProcNomD"", IFNULL(""U_ProcNomR"",'') ""ProcNomR"", IFNULL(""U_ProcNomC"",'') ""ProcNomC"", IFNULL(""U_ProcNomDe"",'') ""ProcNomDe"", IFNULL(""U_ProcNomL"",'') ""ProcNomL"", IFNULL(""U_ProcNomS"",'') ""ProcNomS"", IFNULL(""U_Habili"",'Y') ""Habilitada"", IFNULL(""U_CantLineas"",0) ""CantLineas"" from ""@VID_FEPROCED"" ";
                }
                oRecordSet.DoQuery(s);

                i = 0;
                oDBDSH.Clear();
                while (!oRecordSet.EoF)
                {
                    oDBDSH.InsertRecord(i);
                    oDBDSH.SetValue("DocEntry", i, Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value)));
                    oDBDSH.SetValue("U_TipoDoc", i, (System.String)(oRecordSet.Fields.Item("TipoDoc").Value));
                    //oDBDSH.SetValue("U_TipoDocPE", i, (System.String)(oRecordSet.Fields.Item("TipoDocPE").Value));
                    oDBDSH.SetValue("U_ProcNomE", i, (System.String)(oRecordSet.Fields.Item("ProcNomE").Value));
                    oDBDSH.SetValue("U_ProcNomD", i, (System.String)(oRecordSet.Fields.Item("ProcNomD").Value));
                    oDBDSH.SetValue("U_ProcNomR", i, (System.String)(oRecordSet.Fields.Item("ProcNomR").Value));
                    oDBDSH.SetValue("U_ProcNomC", i, (System.String)(oRecordSet.Fields.Item("ProcNomC").Value));
                    //oDBDSH.SetValue("U_ProcNomDe", i, (System.String)(oRecordSet.Fields.Item("ProcNomDe").Value));
                    //oDBDSH.SetValue("U_ProcNomL", i, (System.String)(oRecordSet.Fields.Item("ProcNomL").Value));
                    //oDBDSH.SetValue("U_ProcNomS", i, (System.String)(oRecordSet.Fields.Item("ProcNomS").Value));
                    oDBDSH.SetValue("U_Habili", i, (System.String)(oRecordSet.Fields.Item("Habilitada").Value));
                    oDBDSH.SetValue("U_CantLineas", i, Convert.ToString((System.Int32)(oRecordSet.Fields.Item("CantLineas").Value)));
                    oRecordSet.MoveNext();
                    i++;
                }

                oDBDSH.InsertRecord(i);
                oDBDSH.SetValue("DocEntry", i, "");
                oDBDSH.SetValue("U_TipoDoc", i, "");
                //oDBDSH.SetValue("U_TipoDocPE", i, "");
                oDBDSH.SetValue("U_ProcNomE", i, "");
                oDBDSH.SetValue("U_ProcNomD", i, "");
                oDBDSH.SetValue("U_ProcNomR", i, "");
                oDBDSH.SetValue("U_ProcNomC", i, "");
                //oDBDSH.SetValue("U_ProcNomDe", i, "");
                //oDBDSH.SetValue("U_ProcNomL", i, "");
                //oDBDSH.SetValue("U_ProcNomS", i, "");
                oDBDSH.SetValue("U_Habili", i, "Y");
                oDBDSH.SetValue("U_CantLineas", i, "60");

                if (GlobalSettings.RunningUnderSQLServer) //TipoDoc
                {
                    s = @"select U1.FldValue 'Code', U1.Descr 'Name' from UFD1 U1 join CUFD U0 on U0.TableID = U1.TableID and U0.FieldID = U1.FieldID where U1.TableID = '@VID_FEPROCED' and U0.AliasID = '{0}'";
                }
                else
                {
                    s = @"select U1.""FldValue"" ""Code"", U1.""Descr"" ""Name"" from ""UFD1"" U1 join ""CUFD"" U0 on U0.""TableID"" = U1.""TableID"" and U0.""FieldID"" = U1.""FieldID"" where U1.""TableID"" = '@VID_FEPROCED' and U0.""AliasID"" = '{0}' ";
                }

                s = String.Format(s, "TipoDoc");
                oRecordSet.DoQuery(s);
                oColumn = (SAPbouiCOM.Column)(oMtx.Columns.Item("TipoDoc"));
                FSBOf.FillComboMtx(oColumn, ref oRecordSet, false);
                //((SAPbouiCOM.Column)oMtx.Columns.Item("TipoDocPE")).Visible = false;

                if (GlobalSettings.RunningUnderSQLServer) //Habilitado
                {
                    s = @"select FldValue 'Code', Descr 'Name' from UFD1 where TableID = '@VID_FEPROCED' and FieldID = 2";
                }
                else
                {
                    s = @"select ""FldValue"" ""Code"", ""Descr"" ""Name"" from ""UFD1"" where ""TableID"" = '@VID_FEPROCED' and ""FieldID"" = 2";
                }
                oRecordSet.DoQuery(s);
                oColumn = (SAPbouiCOM.Column)(oMtx.Columns.Item("Habili"));
                FSBOf.FillComboMtx(oColumn, ref oRecordSet, false);


                //EditText(oForm.Items.Item('CardCode').Specific).Active := True;
                oMtx.LoadFromDataSource();


                oForm.Mode = BoFormMode.fm_OK_MODE;
                oMtx.AutoResizeColumns();
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            oForm.Freeze(false);
            return(Result);
        }//fin InitForm
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            Int32      i;
            TFunctions Param;

            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            try
            {
                oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                Lista = new List <string>();

                FSBOf.LoadForm(xmlPath, "VID_FEMULTISOC.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = true;
                oForm.SupportedModes = -1;             // afm_All

                VID_DelRow   = false;
                VID_DelRowOK = false;

                Param       = new TFunctions();
                Param.SBO_f = FSBOf;

                //oForm.DataBrowser.BrowseBy := "DocEntry";
                oDBDSH = oForm.DataSources.DBDataSources.Item("@VID_FEMULTISOC");
                //oDBDSBases := oForm.DataSources.DBDataSources.Item("@VID_FEMULTISOC");

                // Ok Ad  Fnd Vw Rq Sec
                //        Lista.Add('DocEntry  , f,  f,  t,  f, r, 1');
                //        Lista.Add('Desde     , f,  f,  f,  f, r, 1');
                //        Lista.Add('mtx       , f,  t,  f,  f, n, 1');
                //        FSBOf.SetAutoManaged(var oForm, Lista);

                oMtx = (Matrix)(oForm.Items.Item("mtx").Specific);

                oMtx.AutoResizeColumns();
                //EditText(oForm.Items.Item('CardCode').Specific).Active := True;

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select U_Sociedad
                              ,U_RUT 
                              ,U_Servidor
                              ,U_Base
	                          ,U_Usuario
	                          ,U_Password
	                          ,DocEntry
	                          ,U_Habilitada
                          from [@VID_FEMULTISOC]";
                }
                else
                {
                    s = @"select ""U_Sociedad""
                              ,""U_RUT""
                              ,""U_Servidor""
                              ,""U_Base""
	                          ,""U_Usuario""
	                          ,""U_Password""
	                          ,""DocEntry""
	                          ,""U_Habilitada""
                          from ""@VID_FEMULTISOC"" ";
                }
                oRecordSet.DoQuery(s);

                if (oRecordSet.RecordCount == 0)
                {
                    oMtx.AddRow(1, 1);
                    oMtx.FlushToDataSource();
                    oMtx.AutoResizeColumns();
                }
                else
                {
                    i = 0;
                    oDBDSH.Clear();
                    while (!oRecordSet.EoF)
                    {
                        oDBDSH.InsertRecord(i);
                        oDBDSH.SetValue("U_Sociedad", i, (System.String)(oRecordSet.Fields.Item("U_Sociedad").Value));
                        oDBDSH.SetValue("U_RUT", i, (System.String)(oRecordSet.Fields.Item("U_RUT").Value));
                        oDBDSH.SetValue("U_Servidor", i, (System.String)(oRecordSet.Fields.Item("U_Servidor").Value));
                        oDBDSH.SetValue("U_Base", i, (System.String)(oRecordSet.Fields.Item("U_Base").Value));

                        oDBDSH.SetValue("U_Usuario", i, (System.String)(oRecordSet.Fields.Item("U_Usuario").Value));
                        //s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim());
                        oDBDSH.SetValue("U_Password", i, (System.String)(oRecordSet.Fields.Item("U_Password").Value));

                        oDBDSH.SetValue("DocEntry", i, Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value)));
                        oDBDSH.SetValue("U_Habilitada", i, (System.String)(oRecordSet.Fields.Item("U_Habilitada").Value));
                        i++;
                        oRecordSet.MoveNext();
                    }
                    oDBDSH.InsertRecord(i);
                    oMtx.LoadFromDataSource();
                    oMtx.AutoResizeColumns();
                }



                oForm.Mode = BoFormMode.fm_OK_MODE;
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            oForm.Freeze(false);
            return(Result);
        }//fin InitForm
예제 #21
0
        /// <summary>
        /// carga los valores que se encuentra en el Webservice
        /// </summary>
        /// <param name="oCompany"></param>
        private void deployCurrency(SAPbobsCOM.Company oCompany)
        {
            SAPbobsCOM.Recordset oRS     = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            SAPbobsCOM.SBObob    pSBObob = (SAPbobsCOM.SBObob)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoBridge);

            TasaCambioSBO                  oTasaCambioSBO = new TasaCambioSBO();
            List <TasaCambioSBO>           oTasasCambio   = new List <TasaCambioSBO>();
            DateTime                       Fecha          = DateTime.Now;
            Dictionary <DateTime, Decimal> AuxDict        = new Dictionary <DateTime, decimal>();

            String oSql;
            int    diasAProcesar;

            // Validar definicion de monedas
            if (oCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB)
            {
                oSql = @"SELECT ""CurrCode"", ""CurrName"" , ""ISOCurrCod"" , ""DocCurrCod""  
                        FROM ""OCRN"" 
                        WHERE ""Locked"" = 'N' ";
            }
            else
            {
                oSql = "SELECT CurrCode, CurrName , ISOCurrCod , DocCurrCod " +
                       "FROM OCRN            " +
                       "WHERE Locked = 'N' ";
            }

            oRS.DoQuery(oSql);
            if (oRS.RecordCount > 0)
            {
                if (SBO_VID_Currency.Properties.Settings.Default.DiasAnterioresAProcesar > 0)
                {
                    diasAProcesar = 0;
                }
                else
                {
                    diasAProcesar = SBO_VID_Currency.Properties.Settings.Default.DiasAnterioresAProcesar;
                }

                oLog.LogMsg("Dias a procesar : " + diasAProcesar, "F", "D");

                for (int x = diasAProcesar; x <= 1; x++)
                {
                    Fecha = Fecha.AddDays(x);
                    string dateFormat = Fecha.ToString("yyyy-MM-dd");
                    oLog.LogMsg("Dia: " + dateFormat, "F", "D");
                    string url          = SBO_VID_Currency.Properties.Settings.Default.WEBPage;
                    string responseRest = restGETWhitParameter(url, dateFormat);
                    if (responseRest != "[]")
                    {
                        var listTC = JsonConvert.DeserializeObject <List <TC> >(responseRest);
                        for (int i = 0; i < oRS.RecordCount; i++)  //Monedas en SAP
                        {
                            string moneda              = ((System.String)oRS.Fields.Item("CurrCode").Value).Trim();
                            string monedaISO           = ((System.String)oRS.Fields.Item("ISOCurrCod").Value).Trim();
                            string monedaInternacional = ((System.String)oRS.Fields.Item("DocCurrCod").Value).Trim();
                            for (int y = 0; y < listTC.Count; y++)
                            {
                                if (moneda == listTC[y].codigo)
                                {
                                    oLog.LogMsg("procesado por CurrCode: " + Fecha + " Currency: " + moneda, "F", "D");
                                    UpdateSBOSAP(ref oCompany, Fecha, (Double)listTC[y].valor, ref pSBObob, moneda);
                                    y = listTC.Count;
                                }
                                else
                                {
                                    if (monedaISO == listTC[y].codigo)
                                    {
                                        oLog.LogMsg("procesado por ISOCurrCod: " + Fecha + " Currency: " + monedaISO, "F", "D");
                                        UpdateSBOSAP(ref oCompany, Fecha, (Double)listTC[y].valor, ref pSBObob, moneda);
                                        y = listTC.Count;
                                    }
                                    else
                                    {
                                        if (monedaInternacional == listTC[y].codigo)
                                        {
                                            oLog.LogMsg("procesado por DocCurrCod: " + Fecha + " Currency: " + monedaInternacional, "F", "D");
                                            UpdateSBOSAP(ref oCompany, Fecha, (Double)listTC[y].valor, ref pSBObob, moneda);
                                            y = listTC.Count;
                                        }
                                    }
                                }
                            }
                            oRS.MoveNext();
                        }
                        oRS.MoveFirst();
                    }
                    Fecha = DateTime.Now;
                }
            }
        }
예제 #22
0
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            Int32 i;

            //SAPbouiCOM.EditTextColumn oEditText;
            SAPbouiCOM.CommonSetting oSetting;
            TFunctions Reg;
            bool       Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            try
            {
                oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                Lista = new List <string>();

                FSBOf.LoadForm(xmlPath, "VID_Sucursal.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = true;
                oForm.SupportedModes = -1;             // afm_All

                //        VID_DelRow := true;
                //        VID_DelRowOK := true;

                //oForm.DataBrowser.BrowseBy := "Code";
                oDBDSH = oForm.DataSources.DBDataSources.Item("@VID_FESUC");

                // Ok Ad  Fnd Vw Rq Sec
                Lista.Add("mtx      , f,  t,  f,  f, r, 1");
                //Lista.Add('Name      , f,  t,  t,  f, r, 1');
                //Lista.Add('CardCode  , f,  t,  t,  f, r, 1');
                //FSBOf.SetAutoManaged(var oForm, Lista);

                //oCombo := ComboBox(oForm.Items.Item('TipDoc').Specific);
                //oCombo.ValidValues.Add('33', 'Factura');

                //s := '1';
                //oCombo.Select(s, BoSearchKey.psk_ByValue);

                //        AddChooseFromList();
                oMtx = (Matrix)(oForm.Items.Item("mtx").Specific);
                //        oColumn                    := SAPbouiCOM.Column(oMtx.Columns.Item('V_0'));
                //        oColumn.ChooseFromListUID  := 'CFL0';
                //        oColumn.ChooseFromListAlias:= 'Code';
                //        oMtx.AutoResizeColumns();

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select Code, Name, ISNULL(U_Habilitada,'Y') 'Habilitada' from [@VID_FESUC]";
                }
                else
                {
                    s = @"select ""Code"", ""Name"", IFNULL(""U_Habilitada"",'Y') ""Habilitada"" from ""@VID_FESUC"" ";
                }
                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount == 0)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = "select Code from [@VID_FESUC] where Code = 'Principal'";
                    }
                    else
                    {
                        s = @"select ""Code"" from ""@VID_FESUC"" where ""Code"" = 'Principal' ";
                    }
                    oRecordSet.DoQuery(s);
                    if (oRecordSet.RecordCount == 0)
                    {
                        Reg       = new TFunctions();
                        Reg.SBO_f = FSBOf;
                        oDBDSH.Clear();
                        oDBDSH.InsertRecord(0);
                        oDBDSH.SetValue("Code", 0, "Principal");
                        oDBDSH.SetValue("Name", 0, "SAP BO");
                        oDBDSH.SetValue("U_Habilitada", 0, "Y");
                        if (Reg.FESUCAdd(oDBDSH) == true)
                        {
                            FSBOApp.StatusBar.SetText("Sucursal Principal creada correctamente", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        }
                        else
                        {
                            FSBOApp.StatusBar.SetText("Sucursal Principal no ha sido creada", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                        }
                    }
                }

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select Code, Name, ISNULL(U_Habilitada,'Y') 'Habilitada' from [@VID_FESUC]";
                }
                else
                {
                    s = @"select ""Code"", ""Name"", IFNULL(""U_Habilitada"",'Y') ""Habilitada"" from ""@VID_FESUC"" ";
                }
                oRecordSet.DoQuery(s);
                i = 0;
                oDBDSH.Clear();
                while (!oRecordSet.EoF)
                {
                    oDBDSH.InsertRecord(i);
                    oDBDSH.SetValue("Code", i, (System.String)(oRecordSet.Fields.Item("Code").Value));
                    oDBDSH.SetValue("Name", i, (System.String)(oRecordSet.Fields.Item("Name").Value));
                    oDBDSH.SetValue("U_Habilitada", i, (System.String)(oRecordSet.Fields.Item("Habilitada").Value));
                    oRecordSet.MoveNext();
                    i++;
                }

                oDBDSH.InsertRecord(i);
                oDBDSH.SetValue("Code", i, "");
                oDBDSH.SetValue("Name", i, "");
                oDBDSH.SetValue("U_Habilitada", i, "Y");

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select FldValue 'Code', Descr 'Name' from UFD1 where TableID = '@VID_FESUC' and FieldID = 0";
                }
                else
                {
                    s = @"select ""FldValue"" ""Code"", ""Descr"" ""Name"" from ""UFD1"" where ""TableID"" = '@VID_FESUC' and ""FieldID"" = 0";
                }
                oRecordSet.DoQuery(s);
                oColumn = (SAPbouiCOM.Column)(oMtx.Columns.Item("Habilitada"));
                FSBOf.FillComboMtx(oColumn, ref oRecordSet, false);

                //EditText(oForm.Items.Item('CardCode').Specific).Active := True;
                oMtx.LoadFromDataSource();

                oSetting = oMtx.CommonSetting;
                i        = 1;
                while (i <= oMtx.RowCount)
                {
                    if ((System.String)(oDBDSH.GetValue("Code", i - 1)).Trim() != "")
                    {
                        oSetting.SetCellEditable(i, 1, false);
                    }
                    i++;
                }

                oForm.Mode = BoFormMode.fm_OK_MODE;
                oMtx.AutoResizeColumns();
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            oForm.Freeze(false);
            return(Result);
        }//fin InitForm
예제 #23
0
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            //SAPbouiCOM.ComboBox oComboBox;
            //SAPbouiCOM.Column oColumn;

            Param       = new TFunctions();
            Param.SBO_f = FSBOf;

            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            try
            {
                oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                //Lista    := New list<string>;

                FSBOf.LoadForm(xmlPath, "VID_GELibro.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = false;
                oForm.SupportedModes = -1;       // afm_All

                oForm.EnableMenu("1281", false); //Actualizar
                oForm.EnableMenu("1282", false); //Crear

                oForm.DataSources.UserDataSources.Add("TipoLibro", BoDataType.dt_SHORT_TEXT);
                oComboBox = (ComboBox)(oForm.Items.Item("TipoLibro").Specific);
                oComboBox.DataBind.SetBound(true, "", "TipoLibro");
                oComboBox.ValidValues.Add("V", "Venta");
                oComboBox.ValidValues.Add("C", "Compra");
                oComboBox.Select("V", BoSearchKey.psk_ByValue);

                oForm.DataSources.UserDataSources.Add("Periodo", BoDataType.dt_SHORT_TEXT);
                oComboBox = (ComboBox)(oForm.Items.Item("Periodo").Specific);
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    oRecordSet.DoQuery("select CAST(AbsEntry AS VARCHAR(20)) Code, Code 'Name'  from OFPR where YEAR(F_RefDate) >= YEAR(GETDATE())-1  AND YEAR(T_RefDate) <= YEAR(GETDATE())");
                }
                else
                {
                    oRecordSet.DoQuery(@"select TO_VARCHAR(""AbsEntry"") ""Code"", ""Code"" ""Name""  from ""OFPR"" where YEAR(""F_RefDate"") >= YEAR(NOW())-1  AND YEAR(""T_RefDate"") <= YEAR(NOW()) ");
                }
                FSBOf.FillCombo((ComboBox)(oForm.Items.Item("Periodo").Specific), ref oRecordSet, false);
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select AbsEntry from OFPR where GETDATE() BETWEEN F_RefDate AND T_RefDate";
                }
                else
                {
                    s = @"select ""AbsEntry"" from ""OFPR"" where NOW() BETWEEN ""F_RefDate"" AND ""T_RefDate"" ";
                }
                oRecordSet.DoQuery(s);
                oComboBox.Select(((System.Int32)oRecordSet.Fields.Item("AbsEntry").Value).ToString(), BoSearchKey.psk_ByValue);


                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select ISNULL(U_MultiSoc,'N') MultiSoc from [@VID_FEPARAM]";
                }
                else
                {
                    s = @"select IFNULL(""U_MultiSoc"",'N') ""MultiSoc"" from ""@VID_FEPARAM"" ";
                }
                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    if (((System.String)oRecordSet.Fields.Item("MultiSoc").Value) == "Y")
                    {
                        bMultiSoc = true;
                    }
                }

                if (bMultiSoc)
                {
                    oForm.Items.Item("LInstituto").Visible = true;
                    oForm.Items.Item("Instituto").Visible  = true;
                    oComboBox = (ComboBox)(oForm.Items.Item("Instituto").Specific);
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select DocEntry, U_Sociedad 'Sociedad' from [@VID_FEMULTISOC] where isnull(U_Habilitada,'N') = 'Y'";
                    }
                    else
                    {
                        s = @"select ""DocEntry"", ""U_Sociedad"" ""Sociedad"" from ""@VID_FEMULTISOC"" where IFNULL(""U_Habilitada"",'N') = 'Y' ";
                    }
                    oRecordSet.DoQuery(s);
                    while (!oRecordSet.EoF)
                    {
                        oComboBox.ValidValues.Add(((System.Int32)oRecordSet.Fields.Item("DocEntry").Value).ToString(), ((System.String)oRecordSet.Fields.Item("Sociedad").Value).Trim());
                        oRecordSet.MoveNext();
                    }
                }
                else
                {
                    oForm.Items.Item("LInstituto").Visible = false;
                    oForm.Items.Item("Instituto").Visible  = false;
                }
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            oForm.Freeze(false);
            return(Result);
        }//fin InitForm
예제 #24
0
        }//fin FormEvent

        private void EnviarLibros(String TipoLibro, String FDesde, String FHasta)
        {
            SqlConnection  ConexionADO;
            SqlCommand     SqlComan;
            SqlParameter   oParameter;
            SqlDataAdapter Adapter;
            DataSet        DataSet;
            SqlCommand     cmd;
            Boolean        Paso          = false;
            String         procedimiento = "";
            Int32          iCol;

            try
            {
                sCnn = sConnection();

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select ISNULL(U_ProcVenta,'') ProcVenta, ISNULL(U_ProcCompra,'') ProcCompra from [@VID_FEPARAM]";
                }
                else
                {
                    s = @"select IFNULL(""U_ProcVenta"",'') ""ProcVenta"", IFNULL(""U_ProcCompra"",'') ""ProcCompra"" from ""@VID_FEPARAM"" ";
                }
                oRecordSet.DoQuery(s);

                if (oRecordSet.RecordCount == 0)
                {
                    Paso = false;
                    FSBOApp.StatusBar.SetText("Debe parametrizar el addon", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
                else
                {
                    if ((((System.String)oRecordSet.Fields.Item("ProcVenta").Value).Trim() == "") && (TipoLibro == "V"))
                    {
                        Paso = false;
                        FSBOApp.StatusBar.SetText("Debe ingresar procedimiento para Libro de Venta en parametros del addon Factura Electronica", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }
                    else if ((((System.String)oRecordSet.Fields.Item("ProcCompra").Value).Trim() == "") && (TipoLibro == "C"))
                    {
                        Paso = false;
                        FSBOApp.StatusBar.SetText("Debe ingresar procedimiento para Libro de Compra en parametros del addon Factura Electronica", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }
                    else
                    {
                        Paso = true;
                        if (TipoLibro == "V")
                        {
                            procedimiento = ((System.String)oRecordSet.Fields.Item("ProcVenta").Value).Trim();
                        }
                        else
                        {
                            procedimiento = ((System.String)oRecordSet.Fields.Item("ProcCompra").Value).Trim();
                        }
                    }
                }

                if (Paso == true)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = "exec " + procedimiento + " '" + FDesde + "'" + ", '" + FHasta + "'";
                    }
                    else
                    {
                        s = "CALL " + procedimiento + "  ('" + FDesde + "', '" + FHasta + "')";
                    }

                    oRecordSet.DoQuery(s);
                    if (oRecordSet.RecordCount > 0)
                    {
                        //primero borrar registros previos del periodo
                        ConexionADO = new SqlConnection(sCnn);
                        if (ConexionADO.State == ConnectionState.Closed)
                        {
                            ConexionADO.Open();
                        }
                        cmd = new SqlCommand();
                        cmd.CommandTimeout = 0;
                        cmd.CommandType    = CommandType.Text;
                        cmd.Connection     = ConexionADO;
                        s = "exec DelDocLibroPeriodo '{0}', {1}";
                        s = String.Format(s, FDesde.Substring(0, 6), TipoLibro);
                        cmd.CommandText = s;
                        cmd.ExecuteNonQuery();
                        //fin limpia registros

                        if (TipoLibro == "V")
                        {
                            s = "EInsLibroVentaManual";
                        }
                        else
                        {
                            s = "EInsLibroCompraManual";
                        }

                        SqlComan = new SqlCommand(s, ConexionADO);

                        oParameter           = new SqlParameter();
                        SqlComan.CommandType = CommandType.StoredProcedure;
                        iCol = 0;
                        while (!oRecordSet.EoF)
                        {
                            while (iCol < oRecordSet.Fields.Count)
                            {
                                var NomCol = "@" + oRecordSet.Fields.Item(iCol).Name;
                                s          = oRecordSet.Fields.Item(iCol).Type.ToString();
                                oParameter = SqlComan.Parameters.AddWithValue(NomCol, oRecordSet.Fields.Item(iCol).Value.ToString());

                                OutLog("Parametro  " + NomCol + " - Valor " + oRecordSet.Fields.Item(iCol).Value);
                                iCol++;
                            }
                            Adapter = new SqlDataAdapter(SqlComan);
                            DataSet = new DataSet(SqlComan.CommandText);
                            Adapter.Fill(DataSet);
                            //dyt_id_traspaso = Convert.ToInt32(DataSet.Tables[0].Rows[0][1].ToString());
                            oRecordSet.MoveNext();
                        }
                        FSBOApp.MessageBox("Se han cargado " + oRecordSet.RecordCount + " documentos en el portal");
                    }
                }
            }
            catch (Exception ex)
            {
                FSBOApp.StatusBar.SetText("EnviarLibros: " + ex.Message + " ** Trace: " + ex.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                OutLog("EnviarLibros: " + ex.Message + " ** Trace: " + ex.StackTrace);
            }
        }
예제 #25
0
        public bool ExportPayments(/*DateTime lasttime*/)
        {
            MyLogger.Log("Exportando títulos...");
            try
            {
                SAPbobsCOM.Recordset oRecordset =
                    this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);


                String query = "";
                query = query + "select * from dbo.[LB_titulos]";

                oRecordset.DoQuery(query);

                List <TitulosSAP> titulos = new List <TitulosSAP>();

                while (!oRecordset.EoF)
                {
                    List <Contacts> conts = new List <Contacts>();

                    SAPbobsCOM.Recordset oRecordset2 =
                        this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                    String varname1 = "";
                    varname1 = varname1 + "select *, ROW_NUMBER() over(partition by cardcode order by sort, email,phone) as rownumber " + "\n";
                    varname1 = varname1 + "	from( " + "\n";
                    varname1 = varname1 + "		select distinct  T1.CardCode, "+ "\n";
                    varname1 = varname1 + "		isnull(t0.Name,'') +' - '+ isnull(t0.FirstName,'')  as name, "+ "\n";
                    varname1 = varname1 + "			isnull(t0.E_MailL,t1.E_Mail) as email, "+ "\n";
                    varname1 = varname1 + "			ISNULL(t0.Tel1+ '-','') + ISNULL(t0.Tel2+ ' / ','') + "+ "\n";
                    varname1 = varname1 + "				isnull(t1.Phone1+ '-', '')+ISNULL(t1.Phone2,'') as phone, "+ "\n";
                    varname1 = varname1 + "		case when isnull(t0.E_MailL,t1.E_Mail) is null then '3' else '1' end sort "+ "\n";
                    varname1 = varname1 + "		from OCRD t1 left join OCPR t0 on t0.CardCode = t1.CardCode "+ "\n";
                    varname1 = varname1 + "				 "+ "\n";
                    varname1 = varname1 + "		where t0.Name like ('%fin%') or t0.E_MailL like ('%fin%') "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "		UNION "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "		select distinct  T1.CardCode, "+ "\n";
                    varname1 = varname1 + "			isnull(t0.Name,'') +' - '+ isnull(t0.FirstName,''), "+ "\n";
                    varname1 = varname1 + "			isnull(t0.E_MailL,t1.E_Mail), "+ "\n";
                    varname1 = varname1 + "			ISNULL(t0.Tel1+ '-','') + ISNULL(t0.Tel2+ ' / ','') + "+ "\n";
                    varname1 = varname1 + "					isnull(t1.Phone1+ '-', '')+ISNULL(t1.Phone2,''), "+ "\n";
                    varname1 = varname1 + "			case when isnull(t0.E_MailL,t1.E_Mail) is null then '3' else '2' end"+ "\n";
                    varname1 = varname1 + "				 "+ "\n";
                    varname1 = varname1 + "		from OCRD t1 left join OCPR t0 on t0.CardCode = t1.CardCode "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "	) t0 " + "\n";
                    varname1 = varname1 + "	where CardCode = '" + oRecordset.Fields.Item("cardcode").Value + "' " + "\n";
                    varname1 = varname1 + "	order by cardcode, sort, rownumber";

                    oRecordset2.DoQuery(varname1);


                    while (!oRecordset2.EoF)
                    {
                        Contacts cont = new Contacts(oRecordset2.Fields.Item("name").Value + "",
                                                     oRecordset2.Fields.Item("email").Value + "",
                                                     oRecordset2.Fields.Item("phone").Value + ""
                                                     );

                        conts.Add(cont);

                        oRecordset2.MoveNext();
                    }

                    Payees payee = new Payees(oRecordset.Fields.Item("id_type").Value + "",
                                              oRecordset.Fields.Item("id").Value + "",
                                              oRecordset.Fields.Item("legal_name").Value + "",
                                              null, //trade_name
                                              oRecordset.Fields.Item("email").Value + "",
                                              oRecordset.Fields.Item("phone").Value + "",
                                              null, //accounts
                                              conts
                                              );

                    //inserindo CNPJ sacado
                    SAPbobsCOM.Recordset oRecordset3 =
                        this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                    oRecordset3.DoQuery("select top 1 REPLACE(REPLACE(REPLACE ( TaxIdNum , '.' , '' ), '/',''),'-','') as payer from OADM");

                    //criando o pay_doc_id
                    String payer_doc_id = oRecordset.Fields.Item("transID").Value + "-" + oRecordset.Fields.Item("Line_ID").Value;

                    TitulosSAP titulo = new TitulosSAP(
                        oRecordset3.Fields.Item("payer").Value + "",
                        payee,
                        oRecordset.Fields.Item("value").Value + "",
                        oRecordset.Fields.Item("original_value").Value + "",
                        oRecordset.Fields.Item("currency").Value + "",
                        oRecordset.Fields.Item("due_date").Value + "",
                        oRecordset.Fields.Item("issue_date").Value + "",
                        oRecordset.Fields.Item("tax_doc_id").Value + "",
                        oRecordset.Fields.Item("tax_doc_sec_id").Value + "",
                        oRecordset.Fields.Item("tax_doc_key").Value + "",
                        oRecordset.Fields.Item("installment").Value + "",
                        payer_doc_id,
                        String.Equals(oRecordset.Fields.Item("release").Value + "", "true")
                        );

                    titulos.Add(titulo);

                    oRecordset.MoveNext();
                }

                //String invoice = JsonConvert.SerializeObject(titulos, Formatting.Indented);
                String invoice = JsonConvert.SerializeObject(titulos, Formatting.None);


                json = "{\"batch\": \"" + System.Guid.NewGuid() + "\", \"invoices\":" + invoice + "}";


                System.IO.File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\LiberB1\\path.txt", json);

                oCompany.Disconnect();
                MyLogger.Log("Usuário SAP desconectado.");
                LiberRabbit rabbitsend = new LiberRabbit();
                rabbitsend.Connect();
                rabbitsend.WriteJson(json, "invoice.batch.imported");


                MyLogger.Log("Escrito na fila");

                return(true);
            }
            catch (Exception ex)
            {
                MyLogger.Log("Error 508 - " + ex);
                return(false);
            }
        }
예제 #26
0
        private void FindData2(SAPbouiCOM.Form oForm)
        {
            
            oGrid = (SAPbouiCOM.Grid)oForm.Items.Item("grd1").Specific;
            oMatrix = ((SAPbouiCOM.Matrix)(oForm.Items.Item("mtx1").Specific));
            SAPbouiCOM.DBDataSource oKIS_HR00203_HRD = oForm.DataSources.DBDataSources.Item("@KIS_HR00203_HRD");
            StringBuilder pQuery = new StringBuilder();
            string sQry = string.Empty;

            oForm.Freeze(true);

            oMatrix.Clear();
            oKIS_HR00203_HRD.Clear();

            oRS = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

            try
            {

                #region 조회Query
                pQuery.Clear();
                pQuery.AppendLine(" SELECT                                  ");
                pQuery.AppendLine("  U_CHEKER     AS U_CHEKER               ");
                pQuery.AppendLine(" ,U_EMPNO      AS U_EMPNO                ");
                pQuery.AppendLine(" ,U_EMPNM      AS U_EMPNM                ");
                pQuery.AppendLine(" ,U_JIKGBCD    AS U_JIKGBCD              ");
                pQuery.AppendLine(" ,U_JIKCHKCD   AS U_JIKCHKCD             ");
                pQuery.AppendLine(" ,U_DEPTCD     AS U_DEPTCD               ");
                pQuery.AppendLine(" ,U_CHKRATE    AS U_CHKRATE              ");
                pQuery.AppendLine(" FROM [@KIS_HR00203_HRD]                 ");
                pQuery.AppendLine(" WHERE Code = '{0}' AND U_EMPCD <> 'L'   ");
                pQuery.AppendLine(" ORDER BY U_CHEKER                       ");
                sQry = string.Format(pQuery.ToString(), GRIDCODE);
                #endregion

                oRS.DoQuery(sQry);

                B1Connections.theAppl.StatusBar.SetText("데이터 조회중입니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning); //데이터 조회중입니다


                if (oRS.RecordCount > 0)
                {
                    for (int i = 0; i < oRS.RecordCount; i++)
                    {
                        if (i < oRS.RecordCount)
                        { oKIS_HR00203_HRD.InsertRecord(i); }
                        oKIS_HR00203_HRD.SetValue("U_CHEKER", i, oRS.Fields.Item("U_CHEKER").Value);
                        oKIS_HR00203_HRD.SetValue("U_EMPNO", i, oRS.Fields.Item("U_EMPNO").Value);
                        oKIS_HR00203_HRD.SetValue("U_EMPNM", i, oRS.Fields.Item("U_EMPNM").Value);
                        oKIS_HR00203_HRD.SetValue("U_JIKGBCD", i, oRS.Fields.Item("U_JIKGBCD").Value);
                        oKIS_HR00203_HRD.SetValue("U_JIKCHKCD", i, oRS.Fields.Item("U_JIKCHKCD").Value);
                        oKIS_HR00203_HRD.SetValue("U_DEPTCD", i, oRS.Fields.Item("U_DEPTCD").Value);
                        oKIS_HR00203_HRD.SetValue("U_CHKRATE", i, oRS.Fields.Item("U_CHKRATE").Value);
                        oRS.MoveNext();
                    }
                    oMatrix.LoadFromDataSource();
                    B1Connections.theAppl.StatusBar.SetText("조회완료", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success); //조회완료
                }
                else
                {
                    FN.SetMatrixAddRow(ref oForm, ref oMatrix, ref oKIS_HR00203_HRD, FN.RowSelectMode.None, "U_CHEKER");
                    B1Connections.theAppl.StatusBar.SetText("데이터가 없습니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning); //데이터가 없습니다.
                }

            }
            catch (Exception ex)
            {
                oForm.Freeze(false);
                B1Connections.theAppl.StatusBar.SetText("btnFIND_OnAfterItemPressed " + ex.Message, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);

            }
            finally
            {
                oForm.Freeze(false);
                oGrid = null;
                oMatrix = null;
                oRS = null;
                oKIS_HR00203_HRD = null;

            }
        }
예제 #27
0
        public SBOAddon_DB() : base()
        {
            ors = eCommon.oCompany.GetBusinessObject(BoObjectTypes.BoRecordset) as SAPbobsCOM.Recordset;
            try
            {
                // try see if table exist
                ors.DoQuery("SELECT * FROM [@TWM_SETTINGS]");
                while (!ors.EoF)
                {
                    if (ors.Fields.Item("U_TWM_Settings_Type").Value.ToString() == "Export_XML_Path")
                    {
                        _settings_xml_Path = ors.Fields.Item("U_TWM_Settings_Value").Value.ToString();
                    }
                    else if (ors.Fields.Item("U_TWM_Settings_Type").Value.ToString() == "Save_PO_As_Draft")
                    {
                        _settings_Save_PO_Draft = (ors.Fields.Item("U_TWM_Settings_Value").Value.ToString() == "1");
                    }
                    else if (ors.Fields.Item("U_TWM_Settings_Type").Value.ToString() == "Save_SO_As_Draft")
                    {
                        _settings_Save_SO_Draft = (ors.Fields.Item("U_TWM_Settings_Value").Value.ToString() == "1");
                    }

                    ors.MoveNext();
                }
            }
            catch
            {
                //One or more metadata not found. try to recreate them.
                if (ors != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(ors);
                    ors = null;
                    GC.Collect();
                }

                Tables = new B1DbTable[] {
                    new B1DbTable("@TWM_SETTINGS", "Global Settings table", BoUTBTableType.bott_NoObject)
                };

                Columns = new B1DbColumn[]
                {
                    new B1DbColumn("@TWM_SETTINGS", "TWM_Settings_Type", "Setting Type", BoFieldTypes.db_Alpha, BoFldSubTypes.st_None, 250, new B1WizardBase.B1DbValidValue[0], -1),
                    new B1DbColumn("@TWM_SETTINGS", "TWM_Settings_Value", "Setting Value", BoFieldTypes.db_Alpha, BoFldSubTypes.st_None, 250, new B1WizardBase.B1DbValidValue[0], -1),
                    new B1DbColumn("@TWM_SETTINGS", "TWM_Settings_AddOn", "Setting for which AddOn", BoFieldTypes.db_Alpha, BoFldSubTypes.st_None, 250, new B1WizardBase.B1DbValidValue[0], -1)
                };

                try
                {
                    eCommon.SBO_Application.MetadataAutoRefresh = false;
                    this.Add(eCommon.oCompany);
                    addDefaultSettings();
                }
                catch (Exception ex) { eCommon.SBO_Application.MessageBox(ex.Message); }
                finally
                {
                    eCommon.SBO_Application.MetadataAutoRefresh = true;
                }
            }

            if (ors != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ors);
                ors = null;
                GC.Collect();
            }
        }
        public void IniciarIntegracaoEstoque(SAPbobsCOM.Company oCompany)
        {
            try
            {
                Repositorio repositorio = new Repositorio();

                this.log.WriteLogEstoque("Inicio do Processo de Integração de Estoque");

                WarehouseDAL whsDAL = new WarehouseDAL();

                SAPbobsCOM.Recordset recordset = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                recordset = whsDAL.RecuperarSaldoEstoqueSAP(oCompany);

                if (recordset != null && recordset.RecordCount > 0)
                {
                    for (int i = 0; i < recordset.RecordCount; i++)
                    {
                        try
                        {
                            string _itemCode   = recordset.Fields.Item("ItemCode").Value.ToString();
                            Int16  _onHand     = System.Convert.ToInt16(recordset.Fields.Item("OnHand").Value.ToString());
                            string warehouseId = ConfigurationManager.AppSettings["warehouseId"];

                            if (_itemCode.Equals("003179-055"))
                            {
                                string teste = string.Empty;
                            }

                            Task <HttpResponseMessage> response = repositorio.BuscarItemPorSKU(_itemCode, _onHand, oCompany);

                            if (response.Result.IsSuccessStatusCode)
                            {
                                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, _itemCode, _itemCode, EnumStatusIntegracao.Sucesso, "Estoque atualizado com sucesso.");
                                this.log.WriteLogEstoque("Quantidade de estoque do Produto " + _itemCode + " para o depósito " + warehouseId + " atualizada com sucesso.");
                            }
                            if (Convert.ToInt16(response.Result.StatusCode) == 400)
                            {
                                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, _itemCode, _itemCode, EnumStatusIntegracao.Erro, response.Result.ReasonPhrase);
                                this.log.WriteLogEstoque("Não foi possível atualizar a quantidade de estoque para o produto " + _itemCode + ". Retorno API Vtex: " + response.Result.ReasonPhrase);
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        recordset.MoveNext();
                    }
                }

                if (recordset != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(recordset);
                }

                //Log.WriteLog("Atualização controle executação.");
                // Environment.SetEnvironmentVariable("controleExecucao", DateTime.Now.ToUniversalTime().ToString("s") + "Z");
            }
            catch (Exception e)
            {
                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Estoque, "", "", EnumStatusIntegracao.Erro, e.Message);
                this.log.WriteLogEstoque("Exception IniciarProcessoEstoque " + e.Message);
                throw;
            }
        }
        }//fin FormEvent

        private void ActualizarRegistros()
        {
            TFunctions     Reg;
            SqlDataAdapter Adapter;
            SqlConnection  ConexionADO;
            DataSet        cDataSet;
            String         sCnn;
            int            lRetCode;
            String         User, Pass;

            try
            {
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select TOP 1 * from [@VID_FEPARAM]";
                }
                else
                {
                    s = @"select TOP 1 * from ""@VID_FEPARAM""";
                }

                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    Reg       = new TFunctions();
                    Reg.SBO_f = FSBOf;
                    User      = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value));
                    Pass      = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value));
                    sCnn      = Reg.sConexion((System.String)(oRecordSet.Fields.Item("U_Servidor").Value), (System.String)(oRecordSet.Fields.Item("U_Base").Value), User, Pass);
                    if (sCnn.Substring(0, 1) != "E")
                    {
                        ConexionADO = new SqlConnection(sCnn);
                        if (ConexionADO.State == ConnectionState.Closed)
                        {
                            ConexionADO.Open();
                        }

                        if (GlobalSettings.RunningUnderSQLServer)
                        {
                            s = @"SELECT T0.DocEntry, T1.VisOrder, T0.U_TipoDoc, T1.U_Folio, T1.LineId
                                  FROM [@VID_FEDIST] T0 WITH(nolock)
                                  JOIN [@VID_FEDISTD] T1 WITH(nolock) ON T1.DocEntry = T0.DocEntry
                                 WHERE T1.U_Estado = 'D'
                                   AND T0.U_Sucursal <> 'Principal'
                                ";
                        }
                        else
                        {
                            s = @"SELECT T0.""DocEntry"", T1.""VisOrder"", T0.""U_TipoDoc"", T1.""U_Folio"", T1.""LineId""
                                  FROM ""@VID_FEDIST"" T0
                                  JOIN ""@VID_FEDISTD"" T1 ON T1.""DocEntry"" = T0.""DocEntry""
                                 WHERE T1.""U_Estado"" = 'D'
                                   AND T0.""U_Sucursal"" <> 'Principal'";
                        }

                        oRecordSet.DoQuery(s);
                        ConexionADO = new SqlConnection(sCnn);
                        if (ConexionADO.State == ConnectionState.Closed)
                        {
                            ConexionADO.Open();
                        }

                        while (!oRecordSet.EoF)
                        {
                            var VID_SP_EXISTEFOLIO = new SqlCommand("VID_SP_EXISTEFOLIO", ConexionADO);
                            var oParameter         = new SqlParameter();
                            VID_SP_EXISTEFOLIO.CommandType = CommandType.StoredProcedure;
                            oParameter       = VID_SP_EXISTEFOLIO.Parameters.Add("@TipoDoc", SqlDbType.VarChar, 10);
                            oParameter.Value = (System.String)(oRecordSet.Fields.Item("U_TipoDoc").Value);
                            oParameter       = VID_SP_EXISTEFOLIO.Parameters.Add("@FolioNum", SqlDbType.Int);
                            oParameter.Value = (System.Double)(oRecordSet.Fields.Item("U_Folio").Value);

                            Adapter  = new SqlDataAdapter(VID_SP_EXISTEFOLIO);
                            cDataSet = new DataSet(VID_SP_EXISTEFOLIO.CommandText);
                            Adapter.Fill(cDataSet);
                            s = (System.String)(cDataSet.Tables[0].Rows[0][0].ToString()).Trim();

                            if (s == "Y")
                            {
                                s        = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value));
                                s        = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("LineId").Value));
                                s        = Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value));
                                lRetCode = Reg.ActEstadoFolioUpt((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value), (System.Int32)(oRecordSet.Fields.Item("LineId").Value), (System.Double)(oRecordSet.Fields.Item("U_Folio").Value), (System.String)(oRecordSet.Fields.Item("U_TipoDoc").Value), "", "", "");
                                lRetCode = 1;
                                if (lRetCode == 0)
                                {
                                    FSBOApp.StatusBar.SetText("No se ha actualizado estado de Folio " + Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value)), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                    OutLog("No se ha actualizado estado de Folio " + Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value)));
                                }
                            }

                            VID_SP_EXISTEFOLIO = null;

                            oRecordSet.MoveNext();
                        }

                        if (ConexionADO.State == ConnectionState.Open)
                        {
                            ConexionADO.Close();
                        }

                        Grilla();

                        if (ConexionADO.State == ConnectionState.Open)
                        {
                            ConexionADO.Close();
                        }

                        FSBOApp.StatusBar.SetText("Estado de Folios actualizados", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                    }
                    else
                    {
                        FSBOApp.StatusBar.SetText("Faltan datos Conexion. " + sCnn.Substring(1, sCnn.Length - 1), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }
                }
                else
                {
                    FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
            }
            catch (Exception e)
            {
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
                OutLog("GuardarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin ActualizarRegistros
        public void RetornoNotaFiscal(SAPbobsCOM.Company oCompany)
        {
            try
            {
                if (oCompany.Connected)
                {
                    OrdersDAL orders = new OrdersDAL(oCompany);

                    SAPbobsCOM.Recordset recordSet = (Recordset)oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

                    recordSet = orders.RecuperarNumeroNF();

                    SAPbobsCOM.Recordset tempRecordSet = (Recordset)oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

                    tempRecordSet = orders.RecuperarNumeroNF();

                    if (recordSet != null && recordSet.RecordCount > 0)
                    {
                        while (!recordSet.EoF)
                        {
                            if (!recordSet.EoF)
                            {
                                Repositorio repositorio = new Repositorio();
                                Invoice     invoice     = new Invoice();

                                invoice.type         = "Output";
                                invoice.issuanceDate = recordSet.Fields.Item("invoiceDate").Value.ToString();
                                CultureInfo provider       = CultureInfo.InvariantCulture;
                                DateTime    issuanceDateDT = DateTime.ParseExact(invoice.issuanceDate, "dd/MM/yyyy 00:00:00", provider);

                                invoice.issuanceDate  = issuanceDateDT.ToString("yyyy-MM-dd");
                                invoice.invoiceNumber = recordSet.Fields.Item("invoiceNumber").Value.ToString();
                                invoice.invoiceKey    = recordSet.Fields.Item("nfeKey").Value.ToString();

                                string externalId   = string.Empty;
                                string idOrderVtex  = string.Empty;
                                string idOrderVtex2 = string.Empty;
                                string docSAP       = string.Empty;
                                string docNPV       = string.Empty;

                                externalId   = recordSet.Fields.Item("externalId").Value.ToString();
                                idOrderVtex  = recordSet.Fields.Item("idOrderVtex").Value.ToString();
                                idOrderVtex2 = recordSet.Fields.Item("idOrderVtex2").Value.ToString();
                                docSAP       = recordSet.Fields.Item("docSAP").Value.ToString();
                                docNPV       = recordSet.Fields.Item("docNPV").Value.ToString();

                                invoice.invoiceValue = recordSet.Fields.Item("totalNF").Value.ToString().Replace(",", "");
                                invoice.courier      = recordSet.Fields.Item("shippingMethod").Value.ToString();

                                int    updatePedidoNum = 0;
                                string idPedidoVTEX    = string.Empty;

                                string tempDocNPV = string.Empty;

                                List <ItemNF> listaItem = new List <ItemNF>();

                                for (int j = 0; j < tempRecordSet.RecordCount; j++)
                                {
                                    if (!tempRecordSet.EoF)
                                    {
                                        tempDocNPV = tempRecordSet.Fields.Item("docNPV").Value.ToString();

                                        if (docNPV.Equals(tempDocNPV))
                                        {
                                            ItemNF item = new ItemNF();

                                            item.id       = tempRecordSet.Fields.Item("codItem").Value.ToString();
                                            item.price    = System.Convert.ToInt32(tempRecordSet.Fields.Item("precoItem").Value.ToString().Replace(",", ""));
                                            item.quantity = System.Convert.ToInt32(tempRecordSet.Fields.Item("qtdItem").Value.ToString());

                                            listaItem.Add(item);
                                        }

                                        if (j >= 10)
                                        {
                                            break;
                                        }
                                        tempRecordSet.MoveNext();
                                    }
                                }

                                invoice.items = listaItem;

                                if (!string.IsNullOrEmpty(idOrderVtex))
                                {
                                    idPedidoVTEX = idOrderVtex;
                                }
                                else if (!string.IsNullOrEmpty(idOrderVtex2))
                                {
                                    idPedidoVTEX = idOrderVtex2;
                                }

                                if (!string.IsNullOrEmpty(idOrderVtex) && !string.IsNullOrEmpty(idOrderVtex2))
                                {
                                    //recuperar pedido e validar status
                                    Task <HttpResponseMessage> responseOrder = repositorio.BuscarPedido(idOrderVtex);

                                    if (responseOrder.Result.IsSuccessStatusCode)
                                    {
                                        string jsonPedido = responseOrder.Result.Content.ReadAsStringAsync().Result;

                                        var order = JsonConvert.DeserializeObject <Pedido>(jsonPedido);

                                        if (!order.status.Equals("canceled"))
                                        {
                                            Task <HttpResponseMessage> response = repositorio.RetornoNotaFiscal(invoice, idPedidoVTEX);

                                            if (response.Result.IsSuccessStatusCode)
                                            {
                                                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, docSAP, EnumStatusIntegracao.Sucesso, "Número NF " + invoice.invoiceNumber + " enviado para a Vtex com sucesso.");
                                                this.log.WriteLogPedido("Número NF para o Pedido de Venda " + docSAP + " enviado para a Vtex com sucesso.");

                                                //Atualizando campo de usuário U_EnvioNFVTEX
                                                updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));

                                                if (updatePedidoNum != 0)
                                                {
                                                    this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, docSAP, EnumStatusIntegracao.Erro, "Número NF " + invoice.invoiceNumber + " retornado porém não foi possivél atualizar campo de usuário (U_EnvioNFVTEX) do Pedido de Venda");
                                                    this.log.WriteLogPedido("Falha ao atualizar Pedido de Venda " + docSAP);
                                                }
                                            }
                                            else
                                            {
                                                //serializacao erro:
                                                var stringJSONResp = response.Result.Content.ReadAsStringAsync().Result;

                                                var errorResponse = JsonConvert.DeserializeObject <ErrorResponseNF>(stringJSONResp);

                                                if (errorResponse != null)
                                                {
                                                    this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, externalId, EnumStatusIntegracao.Erro, errorResponse.error.message);
                                                    this.log.WriteLogPedido("Falha ao retornar número da Nota Fiscal " + externalId + " para a Vtex");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, docSAP, EnumStatusIntegracao.Erro, "Pedido com status de \"cancelado\" na VTEX.");
                                            this.log.WriteLogPedido("Pedido com status de \"cancelado\" na VTEX.");

                                            //Atualizando campo de usuário U_EnvioNFVTEX
                                            updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));
                                        }
                                    }
                                }
                                else
                                {
                                    this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, externalId, EnumStatusIntegracao.Erro, "Id do Pedido VTEX (NumAtCard e U_NumPedEXT) do Pedido de Venda " + docNPV + " em branco.");
                                    this.log.WriteLogPedido("Falha ao retornar número da Nota Fiscal " + externalId + " para a Vtex - Id do Pedido VTEX (NumAtCard) do Pedido de Venda " + docNPV + " em branco.");

                                    //Atualizando campo de usuário U_EnvioNFVTEX
                                    updatePedidoNum = orders.AtualizarPedidoVenda(oCompany, Convert.ToInt32(externalId));

                                    if (updatePedidoNum != 0)
                                    {
                                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.NF, idPedidoVTEX, docSAP, EnumStatusIntegracao.Erro, "Número NF " + invoice.invoiceNumber + " retornado porém não foi possivél atualizar campo de usuário (U_EnvioNFVTEX) do Pedido de Venda");
                                        this.log.WriteLogPedido("Falha ao atualizar Pedido de Venda " + docSAP);
                                    }
                                }
                                //recordSet = orders.RecuperarNumeroNF();
                                recordSet.MoveNext();
                            }
                        }
                    }

                    if (recordSet != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(recordSet);
                    }
                }
            }
            catch (Exception e)
            {
                this.log.WriteLogPedido("Exception RetornoNotaFiscal " + e.Message);
                //throw;
            }
        }
        }//fin MenuEvent

        private void ActualizarRegistrosWS()
        {
            String sCode = "";

            //SqlDataAdapter cmd2;
            System.Data.DataTable resultDataTable;
            //System.Data.DataTable resultDataTable1;
            Int32   i;
            Boolean _return;

            SAPbouiCOM.GridColumn oColumn;
            String sDocEntry = "";

            SAPbobsCOM.Recordset orsAux;
            String RUTEmpresa = "";
            String URL        = "";
            String URLFinal;

            String[]    TipoDocs = { "33", "34", "39", "41", "43", "46", "52", "56", "61", "110", "111", "112" };
            String      UserWS   = "";
            String      PassWS   = "";
            String      sMessage;
            String      xmlCAF = "";
            XmlDocument oXml;
            String      Desde = "";
            String      Hasta = "";
            String      Fecha = "";

            try
            {
                ActualizarGrilla();

                orsAux = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"SELECT U_BuscarCAF, ISNULL(U_UserWSCL,'') 'UserWS', ISNULL(U_PassWSCL,'') 'PassWS' FROM [@VID_FEPARAM] WHERE Code = '1'";
                }
                else
                {
                    s = @"SELECT ""U_BuscarCAF"", IFNULL(""U_UserWSCL"",'') ""UserWS"", IFNULL(""U_PassWSCL"",'') ""PassWS"" FROM ""@VID_FEPARAM"" WHERE ""Code"" = '1'";
                }
                orsAux.DoQuery(s);

                if (orsAux.RecordCount == 0)
                {
                    throw new Exception("Debe parametrizar el addon");
                }
                else if (((System.String)orsAux.Fields.Item("U_BuscarCAF").Value).Trim() == "")
                {
                    throw new Exception("Debe ingresar http para buscar CAF en paramatros del addon");
                }
                else
                {
                    URL = ((System.String)orsAux.Fields.Item("U_BuscarCAF").Value).Trim();
                    if (((System.String)orsAux.Fields.Item("UserWS").Value).Trim() != "")
                    {
                        UserWS = Funciones.DesEncriptar(((System.String)orsAux.Fields.Item("UserWS").Value).Trim());
                    }
                    if (((System.String)orsAux.Fields.Item("PassWS").Value).Trim() != "")
                    {
                        PassWS = Funciones.DesEncriptar(((System.String)orsAux.Fields.Item("PassWS").Value).Trim());
                    }
                }

                if (bMultiSoc)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"SELECT DocEntry, REPLACE(REPLACE(ISNULL(U_RUT,''),'.',''),'-','') TaxIdNum FROM [@VID_FEMULTISOC] WHERE U_Habilitada = 'Y'";
                    }
                    else
                    {
                        s = @"SELECT TO_VARCHAR(""DocEntry"") ""DocEntry"", REPLACE(REPLACE(IFNULL(""U_RUT"",''),'.',''),'-','') ""TaxIdNum"" FROM ""@VID_FEMULTISOC"" WHERE ""U_Habilitada"" = 'Y' ";
                    }
                }
                else
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"SELECT REPLACE(REPLACE(ISNULL(TaxIdNum,''),'-',''),'.','') TaxIdNum FROM OADM";
                    }
                    else
                    {
                        s = @"SELECT REPLACE(REPLACE(IFNULL(""TaxIdNum"",''),'-',''),'.','') ""TaxIdNum"" FROM ""OADM"" ";
                    }
                }
                oRecordSet.DoQuery(s);

                if (oRecordSet.RecordCount > 0)
                {
                    while (!oRecordSet.EoF)
                    {
                        try
                        {
                            RUTEmpresa = ((System.String)oRecordSet.Fields.Item("TaxIdNum").Value).Trim();
                            if (bMultiSoc)
                            {
                                sDocEntry = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value));
                            }
                            else
                            {
                                sDocEntry = "0";
                            }

                            foreach (String xTipo in TipoDocs)
                            {
                                try
                                {
                                    //http://portal1.easydoc.cl/consulta/generaciondte.aspx?RUT={0}&TIPODTE={1}&OP=22
                                    URLFinal = URL;
                                    URLFinal = String.Format(URLFinal, RUTEmpresa, xTipo);


                                    WebRequest request = WebRequest.Create(URLFinal);
                                    if ((UserWS != "") && (PassWS != ""))
                                    {
                                        request.Credentials = new NetworkCredential(UserWS, PassWS);
                                    }
                                    request.Method = "POST";
                                    string postData  = "";//** xmlDOC.InnerXml;
                                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                                    request.ContentType   = "text/xml";
                                    request.ContentLength = byteArray.Length;
                                    Stream dataStream = request.GetRequestStream();
                                    dataStream.Write(byteArray, 0, byteArray.Length);
                                    dataStream.Close();
                                    WebResponse response = request.GetResponse();
                                    Console.WriteLine(((HttpWebResponse)(response)).StatusDescription);
                                    dataStream = response.GetResponseStream();
                                    StreamReader reader             = new StreamReader(dataStream);
                                    string       responseFromServer = reader.ReadToEnd();
                                    reader.Close();
                                    dataStream.Close();
                                    response.Close();
                                    sMessage = responseFromServer;
                                    request  = null;
                                    response = null;
                                    GC.Collect();
                                    GC.WaitForPendingFinalizers();

                                    if (sMessage != "")
                                    {
                                        xmlCAF = sMessage;
                                        xmlCAF = xmlCAF.Replace(@"<?xml version=""1.0""?>", "");
                                        //xmlCAF = xmlCAF.Replace("\n", "");
                                        //xmlCAF = xmlCAF.Replace(@"\", "");
                                        //xmlCAF = xmlCAF.Replace(Environment.NewLine, "");
                                        oXml = new XmlDocument();
                                        oXml.LoadXml(xmlCAF);

                                        var DA  = oXml.GetElementsByTagName("DA");
                                        var RNG = ((XmlElement)DA[0]).GetElementsByTagName("RNG");
                                        foreach (XmlElement nodo in RNG)
                                        {
                                            var nDesde = nodo.GetElementsByTagName("D");
                                            var nHasta = nodo.GetElementsByTagName("H");
                                            Desde = (System.String)(nDesde[0].InnerText);
                                            Hasta = (System.String)(nHasta[0].InnerText);
                                        }

                                        var CAF = oXml.GetElementsByTagName("CAF");
                                        var DA2 = ((XmlElement)CAF[0]).GetElementsByTagName("DA");
                                        foreach (XmlElement nodo in CAF)
                                        {
                                            var nFecha = nodo.GetElementsByTagName("FA");
                                            Fecha = (System.String)(nFecha[0].InnerText);
                                        }

                                        if (GlobalSettings.RunningUnderSQLServer)
                                        {
                                            s = @"SELECT Code
                                          FROM [@VID_FECAF]
                                         WHERE U_TipoDoc = '{0}'
                                           AND U_Desde = {1}
                                           AND U_Hasta = {2}
                                           {3}";
                                        }
                                        else
                                        {
                                            s = @"SELECT ""Code""
                                          FROM ""@VID_FECAF""
                                         WHERE ""U_TipoDoc"" = '{0}'
                                           AND ""U_Desde"" = {1}
                                           AND ""U_Hasta"" = {2}
                                            {3}";
                                        }
                                        s = String.Format(s, xTipo, Desde, Hasta, (bMultiSoc ? " AND U_BaseMul = " + sDocEntry : ""));
                                        orsAux.DoQuery(s);
                                        if (orsAux.RecordCount == 0) //no existe en la base de datos
                                        {
                                            sCode = Funciones.sNuevoDocEntryLargo("@VID_FECAF", GlobalSettings.RunningUnderSQLServer);
                                            oDBDSH.Clear();
                                            oDBDSH.InsertRecord(0);
                                            oDBDSH.SetValue("Code", 0, sCode);
                                            //OutLog("Code -> " + oDBDSH.GetValue("Code",0));
                                            oDBDSH.SetValue("U_TipoDoc", 0, xTipo);
                                            //OutLog("TipoDoc -> " + oDBDSH.GetValue("U_TipoDoc", 0));
                                            oDBDSH.SetValue("U_Desde", 0, Desde);
                                            //OutLog("Desde -> " + oDBDSH.GetValue("U_Desde", 0));
                                            oDBDSH.SetValue("U_Hasta", 0, Hasta);
                                            //OutLog("Hasta -> " + oDBDSH.GetValue("U_Hasta", 0));
                                            DateTime oFecha;
                                            DateTime.TryParse(Fecha, out oFecha);
                                            oDBDSH.SetValue("U_Fecha", 0, oFecha.ToString("yyyyMMdd"));
                                            //OutLog("Fecha -> " + oDBDSH.GetValue("U_Fecha", 0));
                                            oDBDSH.SetValue("U_BaseMul", 0, sDocEntry);
                                            //OutLog("BaseMul -> " + oDBDSH.GetValue("U_BaseMul", 0));
                                            oDBDSH.SetValue("U_CAF", 0, xmlCAF);
                                            //OutLog("CAF -> " + oDBDSH.GetValue("U_CAF", 0));
                                            oDBDSH.SetValue("U_Utilizados", 0, "0");
                                            //OutLog("Utilizados -> " + oDBDSH.GetValue("U_Utilizados", 0));
                                            var iDif = (Convert.ToInt32(Hasta) - Convert.ToInt32(Desde)) + 1;
                                            oDBDSH.SetValue("U_Asignables", 0, iDif.ToString());
                                            //OutLog("Asignables -> " + oDBDSH.GetValue("U_Asignables", 0));
                                            oDBDSH.SetValue("U_FolioDesde", 0, Desde);
                                            //OutLog("FolioDesde -> " + oDBDSH.GetValue("U_FolioDesde", 0));
                                            _return = Funciones.CAFAdd(oDBDSH);
                                            if (_return)
                                            {
                                                FSBOApp.StatusBar.SetText("CAF Registrado, TipoDoc " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                            }
                                            else
                                            {
                                                FSBOApp.StatusBar.SetText("CAF no se ha registrado, TipoDoc " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        FSBOApp.StatusBar.SetText("No se ha encontrado CAF para documento " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                    }
                                }
                                catch (Exception v)
                                {
                                    OutLog("Error actualizar CAF Tipo " + xTipo + " RUT Empresa " + RUTEmpresa + ", " + v.Message + ", TRACE " + v.StackTrace);
                                    FSBOApp.StatusBar.SetText("Error actualizar CAF Tipo " + xTipo + " RUT Empresa " + RUTEmpresa + ", " + v.Message, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                }
                            }//Fin Foreach
                            FSBOApp.StatusBar.SetText("CAF actualizados", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        }
                        catch (Exception v)
                        {
                            OutLog("Error actualizar empresa RUT " + RUTEmpresa + ", " + v.Message + ", TRACE " + v.StackTrace);
                            FSBOApp.StatusBar.SetText("Error actualizar empresa RUT " + RUTEmpresa + ", " + v.Message, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                        }
                        oRecordSet.MoveNext();
                    }

                    ActualizarGrilla();
                }
                else
                {
                    FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
            }
            catch (Exception e)
            {
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
                OutLog("ActualizarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin ActualizarRegistros
예제 #32
0
        /// <summary>
        /// 분개 저장 TR_COMMON.JournalType 에 따라 분개, 분개취소 전표를 발행한다.
        /// </summary>
        private bool DI_JournalEntries(SAPbouiCOM.Form oForm, SO.SO_COMMON_HRD.JournalType pJournalType)
        {
            bool boolReturn = true;

            int? retValue = null;
            int nError;
            string strError = string.Empty;

            string strJournalEntry = string.Empty;
            //string xSQL = string.Empty;
            StringBuilder sb;

            string xSQL = string.Empty;

            //DateTime dateDoc = DateTime.Today;
            //string strDate = string.Empty;

            string strHEAD_MEMO = string.Empty;
            string strLINE_MEMO = string.Empty;


            string strDocEntry = string.Empty;
            string strPaperType = string.Empty;
            string strCENTNM = string.Empty;
            string strDESC = string.Empty;
            string strDOCDT = string.Empty;

            string strAccount = string.Empty;
            string strDebit = string.Empty;
            string strCredit = string.Empty;
            string strShortName = string.Empty;
            string strCostCd = string.Empty;

            SAPbobsCOM.JournalEntries oJournalEntries = null;
            try
            {
                oDB_M = oForm.DataSources.DBDataSources.Item("@KIS_SO0320T_HRD");
                oDB_1 = oForm.DataSources.DBDataSources.Item("@KIS_SO03201_HRD");
                strDocEntry = oDB_M.GetValue("DocEntry", 0).Trim();
                strDOCDT = oDB_M.GetValue("U_DOCDT", 0).Trim();
                strCENTNM = oDB_M.GetValue("U_CENTNM", 0).Trim();
                strDESC = oDB_M.GetValue("U_DESC", 0).Trim();

                oRS = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                oJournalEntries = (SAPbobsCOM.JournalEntries)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oJournalEntries);

                /*##### 트랙젝션 시작 #####*/
                B1Connections.diCompany.StartTransaction();

                if (pJournalType == SO.SO_COMMON_HRD.JournalType.A01)
                {
                    xSQL = string.Format(" EXEC KIS_SP_SO0320F1_HRD @pDocEntry = {0} ", strDocEntry);
                    oRS.DoQuery(xSQL);
                    if (!oRS.EoF)
                    {
                        // 헤더셋팅
                        strHEAD_MEMO = "[" + strCENTNM + "] " + strDESC;

                        oJournalEntries.ReferenceDate = Convert.ToDateTime(FN.SetDateFormatToDB(strDOCDT)); //전기일
                        oJournalEntries.DueDate = Convert.ToDateTime(FN.SetDateFormatToDB(strDOCDT));   //만기일
                        oJournalEntries.TaxDate = Convert.ToDateTime(FN.SetDateFormatToDB(strDOCDT));   //증빙일
                        oJournalEntries.Memo = strHEAD_MEMO;
                        oJournalEntries.UserFields.Fields.Item("U_ADDOCTP").Value = "KIS_SO0320_HRD";
                        oJournalEntries.UserFields.Fields.Item("U_BPLID").Value = "1";

                        for (int i = 0; i < oRS.RecordCount; i++)
                        {
                            strAccount = oRS.Fields.Item("ACCOUNT").Value.ToString();
                            strDebit = oRS.Fields.Item("DEBIT").Value.ToString(); //차변
                            strCredit = oRS.Fields.Item("CREDIT").Value.ToString(); //대변
                            strShortName = oRS.Fields.Item("SHORTNM").Value.ToString();
                            strLINE_MEMO = oRS.Fields.Item("MEMO").Value.ToString(); //헤더,라인 메모
                            strCostCd = oRS.Fields.Item("COSTCD").Value.ToString(); // 코스트센터 (운반비 적용시 코스트센터 적용)

                            //기본적으로 Count는 1개이다.
                            if (i > 0)
                                oJournalEntries.Lines.Add();

                            oJournalEntries.Lines.AccountCode = strAccount;
                            oJournalEntries.Lines.LineMemo = strLINE_MEMO;

                            // 거래처코드(관리계정일경우 거래처코드 입력)
                            if (!string.IsNullOrEmpty(strShortName))
                                oJournalEntries.Lines.ShortName = strShortName;

                            // 코스트센터 (운반비 적용시 코스트센터 적용)
                            if (!string.IsNullOrEmpty(strCostCd))
                                oJournalEntries.Lines.CostingCode = strCostCd;

                            if (double.Parse(strDebit) != 0.0)
                            {
                                oJournalEntries.Lines.Debit = double.Parse(strDebit);
                            }
                            else
                            {
                                oJournalEntries.Lines.Credit = double.Parse(strCredit);
                            }
                            oRS.MoveNext();
                        }
                    }

                    // 분개라인이 생성되지 않을을경우 분개를 추가 하지 않는다.기본적으로 Count는 1개이다.
                    if (oJournalEntries.Lines.Count > 1)
                        retValue = oJournalEntries.Add();
                }
                else if (pJournalType == SO.SO_COMMON_HRD.JournalType.A02)
                {
                    // 분개 취소시 분개번호는 존재하고 , 분개 취소번호는 없는경우만 분개취소를 실행한다.
                    if (!string.IsNullOrEmpty(oDB_M.GetValue("U_JDTDOC", 0).Trim()) && string.IsNullOrEmpty(oDB_M.GetValue("U_RJDTDOC", 0).Trim()))
                    {
                        oJournalEntries.GetByKey(int.Parse(oDB_M.GetValue("U_JDTDOC", 0).Trim()));
                        retValue = oJournalEntries.Cancel();
                    }
                }

                if (retValue != 0)
                {
                    /*##### 트랙젝션 롤백 #####*/
                    if (B1Connections.diCompany.InTransaction == true)
                    {
                        B1Connections.diCompany.EndTransaction(BoWfTransOpt.wf_RollBack);
                    }

                    B1Connections.diCompany.GetLastError(out nError, out strError);
                    B1Connections.theAppl.StatusBar.SetText("분개 저장이 실패했습니다. " + strError, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                    boolReturn = false;
                }
                else
                {
                    // 분개라인이 존재할경우 키값을 가져온다.
                    if (oJournalEntries.Lines.Count > 1)
                        strJournalEntry = B1Connections.diCompany.GetNewObjectKey();
                    else
                        strJournalEntry = "";


                    if (!string.IsNullOrEmpty(strJournalEntry))
                    {
                        if (pJournalType == SO.SO_COMMON_HRD.JournalType.A01)
                        {
                            sb = new StringBuilder();
                            sb.AppendLine(" UPDATE [@KIS_SO0320T_HRD] SET U_JDTDOC ='{0}' WHERE DocEntry = {1} ");
                        }
                        else
                        {
                            sb = new StringBuilder();
                            sb.AppendLine("  --1.지대수금_헤더 상태값 UPDATE                 ");
                            sb.AppendLine("  UPDATE [@KIS_SO0320T_HRD]                       ");
                            sb.AppendLine("     SET U_RJDTDOC = {0}, Status = 'C'  ");
                            sb.AppendLine("   WHERE DocEntry = {1}                           ");
                            sb.AppendLine("                                                  ");
                            sb.AppendLine("  --2.지대청구_라인(청구입금TRAN) 데이터 삭제     ");
                            sb.AppendLine("  DELETE [@KIS_SO03103_HRD]                       ");
                            sb.AppendLine("   WHERE U_BTYPE = 'KIS_SO0320_HRD' AND U_BENTRY = {1} ");
                            sb.AppendLine("                                                  ");
                            sb.AppendLine("  --3.지대청구_라인(보증금TRAN) 데이터 삭제       ");
                            sb.AppendLine("  DELETE [@KIS_SO03102_HRD]                       ");
                            sb.AppendLine("   WHERE U_BTYPE = 'KIS_SO0320_HRD' AND U_BENTRY = {1} ");

                            sb.AppendLine("   -- 선수금입금_라인                                                                      ");
                            sb.AppendLine("   DELETE A                                                                                ");
                            sb.AppendLine("     FROM [@KIS_SO04201_HRD] A INNER JOIN [@KIS_SO0420T_HRD] B ON A.DocEntry = B.DocEntry  ");
                            sb.AppendLine("    WHERE B.U_BENTRY = {1} AND B.U_BTYPE = 'KIS_SO0320_HRD'                                ");
                            sb.AppendLine("                                                                                           ");
                            sb.AppendLine("   -- 선수금입금_헤더                                                                      ");
                            sb.AppendLine("   DELETE [@KIS_SO0420T_HRD]                                                               ");
                            sb.AppendLine("    WHERE U_BENTRY = {1} AND U_BTYPE = 'KIS_SO0320_HRD'                                    ");
                        }
                        oRS.DoQuery(string.Format(sb.ToString(), strJournalEntry, strDocEntry));

                        /*##### 트랙젝션 커밋 #####*/
                        if (B1Connections.diCompany.InTransaction == true)
                        {
                            B1Connections.diCompany.EndTransaction(BoWfTransOpt.wf_Commit);
                        }

                        GetDataLoad(oForm, strDocEntry);
                    }

                    if (pJournalType == SO.SO_COMMON_HRD.JournalType.A01)
                        B1Connections.theAppl.StatusBar.SetText("분개전기 완료 되었습니다. " + strError, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
                    else
                        B1Connections.theAppl.StatusBar.SetText("분개전기 취소 되었습니다. " + strError, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
                }
                oJournalEntries = null;
            }

            catch (Exception ex)
            {
                B1Connections.theAppl.StatusBar.SetText("DI_JournalEntries " + ex.Message, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
            }
            finally
            {
                /*##### 트랙젝션 롤백 #####*/
                if (B1Connections.diCompany.InTransaction == true)
                {
                    B1Connections.diCompany.EndTransaction(BoWfTransOpt.wf_RollBack);
                }

                if (oRS != null) { Marshal.ReleaseComObject(oRS); } oRS = null;
                if (oJournalEntries != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oJournalEntries);
                    oJournalEntries = null;
                }
            }
            return boolReturn;
        }
예제 #33
0
        /// <summary>
        /// Check if User's input value is valid or not.
        /// </summary>
        /// <param name="rsConfigData"></param>
        /// <returns>If input is invalid, return value starts with "Invalid". If input is valid, return "".</returns>
        public static string CheckIfValidOrNot(SAPbobsCOM.Recordset rsConfigData)
        {
            try
            {
                string controlName     = rsConfigData.Fields.Item("U_ControlName").Value.ToString();
                string controlType     = rsConfigData.Fields.Item("U_ControlType").Value.ToString();
                string accessMatrixKey = rsConfigData.Fields.Item("U_AccessMatrixKey").Value.ToString();
                string itemId          = rsConfigData.Fields.Item("U_ItemId").Value.ToString();
                string colId           = rsConfigData.Fields.Item("U_ColumnId").Value.ToString();
                string input           = GetInputValue(itemId, colId, controlType);
                string result          = String.Empty;

                SAPbobsCOM.Recordset rs = null;

                //Retrieve valid data according to the control name.
                if (controlName == "Business Partner")
                {
                    rs = GetBusinessPartnersByUser();
                }
                else if (controlName == "Business Partner Name")
                {
                    rs = GetBusinessPartnerNamesByUser();
                }
                else if (controlName == "All Business Partner Group")
                {
                    rs = GetAllBusinessPartnerGroups();
                }
                else if (controlName.StartsWith("Dimension")) //Dimension by Branch
                {
                    string branch        = "";
                    string relatedItemId = rsConfigData.Fields.Item("U_RelatedItem").Value.ToString();
                    string relatedColId  = rsConfigData.Fields.Item("U_RelatedColumn").Value.ToString();
                    bool   isBranchId    = false;

                    //Use Dynamic because Control Type can be identified only during runtime. It depends on the document types.
                    //If Control type is ComboBox, branch value from UI is ID.
                    //If Control type is EditText, branch value from UI is Value.
                    dynamic BranchControl = AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId).Specific;
                    if (BranchControl is SAPbouiCOM.ComboBox)
                    {
                        branch     = ((SAPbouiCOM.ComboBox)AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId).Specific).Value;
                        isBranchId = true;
                    }
                    else //if(BranchControl is SAPbouiCOM.EditText)
                    {
                        branch     = ((SAPbouiCOM.EditText)AddOnUtilities.oApplication.Forms.ActiveForm.Items.Item(relatedItemId).Specific).Value;
                        isBranchId = false;
                    }

                    rs = GetDimensionsByBranch(controlName, branch, isBranchId);
                }
                else if (controlName == "Project")
                {
                    rs = GetProjectsByUser();
                }
                else if (controlName == "All Users")
                {
                    rs = GetUsers();
                }
                else if (controlName == "All Projects")
                {
                    rs = GetProjects();
                }
                else if (controlName.Contains("Dimension"))
                {
                    string dimensionType = controlName.ElementAt(controlName.Length - 1).ToString();
                    switch (dimensionType)
                    {
                    case "1":
                        rs = GetDimension1();
                        break;

                    case "2":
                        rs = GetDimension2();
                        break;

                    case "3":
                        rs = GetDimension3();
                        break;

                    case "4":
                        rs = GetDimension4();
                        break;

                    case "5":
                        rs = GetDimension5();
                        break;
                    }
                }
                else if (controlName == "All Branches")
                {
                    rs = GetBranches();
                }
                else if (controlName == "G/L Account")
                {
                    rs = GetAccountsByUser();
                }
                else if (controlName == "All Accounts")
                {
                    rs = GetAllAccounts();
                }

                //Retrieve user's input value.
                //input = GetInputValue(itemId, colId, controlType);

                // Below switch case statement is used to identify which kind of data is valid/invalid. So that error can be showed as "Invalid Input Type (Project, User, Dimension, etc.)
                // Check if user's input is in valid values.
                switch (accessMatrixKey)
                {
                //------------------------------------------------------------------------ Checking for Projects ------------------------------------------------------------------------//
                case "1":     // Projects by User
                case "5":     // All Projects
                    if (input != "")
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid Project.");
                    }
                    break;
                //------------------------------------------------------------------------ End of Checking for Projects ------------------------------------------------------------------------//

                //------------------------------------------------------------------------ Checking for Dimensions ------------------------------------------------------------------------//
                case "2":            // Dimensions by Branch
                case "6":            // All Dimension 1
                case "7":            // All Dimension 2
                case "8":            // All Dimension 3
                case "9":            // All Dimension 4
                case "10":           // All Dimension 5
                    if (input != "") // To check if project column is blank or not first.
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid Dimension.");
                    }
                    break;
                //------------------------------------------------------------------------ End of Checking for Dimensions ------------------------------------------------------------------------//

                //------------------------------------------------------------------------ Checking for Business Partners ------------------------------------------------------------------------//
                case "3":     // Business Partners by User
                case "12":    // All Business Partners
                    if (input != "")
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid Business Partner.");
                    }
                    break;
                //------------------------------------------------------------------------ End of Checking for Business Partners ------------------------------------------------------------------------//

                //------------------------------------------------------------------------ Start of Checking for G/L Account ------------------------------------------------------------------------//
                case "13":     // Chart of Accounts By User
                    if (input != "")
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid Account Code.");
                    }
                    break;
                //------------------------------------------------------------------------ End of Checking for G/L Account ------------------------------------------------------------------------//

                //------------------------------------------------------------------------ Checking for Users ------------------------------------------------------------------------//
                case "4":            // All Users
                    if (input != "") // To check if project column is blank or not first.
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid User.");
                    }
                    break;

                //------------------------------------------------------------------------ End of Checking for Users ------------------------------------------------------------------------//
                case "11":
                    if (input != "")     // To check if project column is blank or not first.
                    {
                        while (!rs.EoF)
                        {
                            string retrievedData = rs.Fields.Item(0).Value.ToString();
                            rs.MoveNext();
                            if (input == retrievedData)
                            {
                                return("");
                            }
                        }
                        return("Invalid Branch.");
                    }
                    break;

                default:
                    break;
                }
                return("");
            }
            catch (Exception ex)
            {
                AddOnUtilities.MsgBoxWrapper(ex.Message + " " + ex.StackTrace);
                return(ex.Message + " " + ex.StackTrace);
            }
        }
예제 #34
0
        /// <summary>
        /// Obtener lista de vouchers por filtro.
        /// </summary>
        public IList <Vouchers> GetVouchersList(SearchVouchersDTO pObjSearchVouchersDTO)
        {
            List <Vouchers> lLstObjVouchers = new List <Vouchers>();

            SAPbobsCOM.Recordset lObjRecordset = null;
            try
            {
                string lStrQuery = this.GetSQL("GetVoucher");
                Dictionary <string, string> lLstStrParameters = new Dictionary <string, string>();
                foreach (string lStrFilter in GetFilterssVouchers(pObjSearchVouchersDTO, lLstStrParameters))
                {
                    lStrQuery += " " + lStrFilter;
                }

                lStrQuery += " order by Code desc";

                //this.UIAPIRawForm.DataSources.DataTables.Item("RESULT").ExecuteQuery(lStrQuery);

                lObjRecordset = (SAPbobsCOM.Recordset)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                lStrQuery     = lStrQuery.Inject(lLstStrParameters);

                lObjRecordset.DoQuery(lStrQuery);

                if (lObjRecordset.RecordCount > 0)
                {
                    for (int i = 0; i < lObjRecordset.RecordCount; i++)
                    {
                        Vouchers lObjVoucher = new Vouchers();
                        lObjVoucher.RowCode  = lObjRecordset.Fields.Item("Code").Value.ToString();
                        lObjVoucher.Folio    = lObjRecordset.Fields.Item("U_Folio").Value.ToString();
                        lObjVoucher.Status   = Convert.ToInt32(lObjRecordset.Fields.Item("U_Status").Value.ToString());
                        lObjVoucher.Area     = lObjRecordset.Fields.Item("U_Area").Value.ToString();
                        lObjVoucher.Employee = lObjRecordset.Fields.Item("U_Employee").Value.ToString();

                        lObjVoucher.Date  = Convert.ToDateTime(lObjRecordset.Fields.Item("U_Date").Value.ToString());
                        lObjVoucher.Total = Convert.ToDouble(lObjRecordset.Fields.Item("U_Total").Value.ToString());
                        double lDblTotal = Convert.ToDouble((lObjRecordset.Fields.Item("DocTotal").Value.ToString()));
                        if (lObjVoucher.Total == lDblTotal && lObjVoucher.Status == (int)StatusEnum.Authorized_Ope_Admon)
                        {
                            //lObjVoucher.Status = 5;
                            if (mObjPurchaseServiceFactory.GetVouchersService().Update(lObjVoucher.RowCode, StatusEnum.Closed) != 0)
                            {
                                string lStrerror = DIApplication.Company.GetLastErrorDescription();
                                UIApplication.ShowMessageBox(lStrerror);
                            }
                            else
                            {
                                lObjVoucher.Status = (int)StatusEnum.Closed; // lObStatusEnum.GetDescription();
                            }
                        }

                        lLstObjVouchers.Add(lObjVoucher);
                        lObjRecordset.MoveNext();
                    }
                }
            }
            catch (Exception ex)
            {
                UIApplication.ShowMessageBox(string.Format("InitDataSourcesException: {0}", ex.Message));
                LogService.WriteError("PurchasesDAO (GetVouchersList): " + ex.Message);
                LogService.WriteError(ex);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjRecordset);
            }

            return(lLstObjVouchers);
        }