Пример #1
0
        /// <summary>
        /// cancela un documento por DocEntry
        /// </summary>
        public bool CancelDocument(string pStrDocEntry)
        {
            try
            {
                SAPbobsCOM.Documents lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices);
                lObjDocument.GetByKey(Convert.ToInt32(pStrDocEntry));
                var lObjCancelDoc = lObjDocument.CreateCancellationDocument();
                lObjCancelDoc.DocDate = DateTime.Now;

                if (lObjCancelDoc.Add() != 0)
                {
                    UIApplication.ShowMessageBox(DIApplication.Company.GetLastErrorDescription());
                    LogService.WriteError("InvoiceDI (AddVoucherDetail) DocEntry:" + pStrDocEntry + " Mensaje:" + DIApplication.Company.GetLastErrorDescription());
                    return(false);
                }
                else
                {
                    LogService.WriteSuccess("Documento cancelado correctamente: " + pStrDocEntry);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                LogService.WriteError("InvoiceDI (CancelDocument) " + ex.Message);
                LogService.WriteError(ex);
                return(false);
            }
        }
Пример #2
0
        public string postDocument(double amount)
        {
            string outStr = "";

            try
            {
                SAPbobsCOM.Documents        Doc = (SAPbobsCOM.Documents)Program.objHrmsUI.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices);
                SAPbobsCOM.BusinessPartners bp  = (SAPbobsCOM.BusinessPartners)Program.objHrmsUI.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners);

                SAPbouiCOM.EditText OWORDocNum = (SAPbouiCOM.EditText)oForm.Items.Item("18").Specific;
                string oworNum = OWORDocNum.Value.ToString();
                oworEntry = Convert.ToString(Program.objHrmsUI.getScallerValue("Select DocEntry from owor where docnum='" + oworNum + "'"));

                Doc.CardCode = txSupplier.Value.ToString();
                Doc.DocDate  = DateTime.ParseExact(txPostingDate.Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                //  Doc.DocDueDate = Convert.ToDateTime(dtORDR.GetValue("CCDate", 0));
                Doc.NumAtCard = txRef.Value.ToString();
                Doc.DocType   = BoDocumentTypes.dDocument_Service;

                Doc.Lines.AccountCode = txEA.Value.ToString();
                Doc.Lines.LineTotal   = amount;
                Doc.Lines.Add();


                try
                {
                    if (Doc.Add() != 0)
                    {
                        int    erroCode = 0;
                        string errDescr = "";
                        Program.objHrmsUI.oCompany.GetLastError(out erroCode, out errDescr);
                        outStr = "Error:" + errDescr + outStr;
                        oApplication.StatusBar.SetText("Failed to post Order : " + errDescr);
                    }
                    else
                    {
                        outStr = Convert.ToString(Program.objHrmsUI.oCompany.GetNewObjectKey());
                        string strUpdate = "Update OWOR set U_CostAP = '" + outStr + "' WHERE DocEntry = '" + oworEntry + "'";
                        Program.objHrmsUI.ExecQuery(strUpdate, "Marking AP");

                        oApplication.StatusBar.SetText("Sales AP Posted Successfully for ", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        oApplication.Menus.Item("1304").Activate();
                    }
                }
                catch (Exception ex)
                {
                    oApplication.StatusBar.SetText("Failed in Exec Query on Posting Document.  : " + ex.Message);
                }
                finally
                {
                }
            }
            catch (Exception ex)
            {
                oApplication.SetStatusBarMessage("Error in posting document : " + ex.Message);
            }
            return(outStr);
        }
Пример #3
0
        public TransactionEntity Create(InvoiceEntity invoice, List <ItemEntity> items)
        {
            int               line        = 0;
            string            newEntityId = "";
            TransactionEntity transaction = new TransactionEntity();

            _Invoice           = Company.GetBusinessObject(BoObjectTypes.oInvoices);
            _Invoice.CardCode  = invoice.CustomerCode;
            _Invoice.NumAtCard = invoice.Reference;
            _Invoice.DocDate   = invoice.DocDate;
            _Invoice.TaxDate   = invoice.TaxDate;
            _Invoice.DocType   = BoDocumentTypes.dDocument_Items;
            _Invoice.Comments  = invoice.Comments;

            foreach (ItemEntity item in items)
            {
                _Invoice.Lines.SetCurrentLine(line);
                _Invoice.Lines.ItemCode      = item.ItemCode;
                _Invoice.Lines.WarehouseCode = item.WarehouseCode;
                _Invoice.Lines.Quantity      = item.Quantity;
                _Invoice.Lines.VatGroup      = item.VatGroup;
                _Invoice.Lines.UnitPrice     = item.UnitPrice;
                _Invoice.Lines.LineTotal     = item.LineTotal;
                _Invoice.Lines.TaxCode       = item.TaxCode;
                _Invoice.Lines.BaseType      = (int)BoObjectTypes.oOrders;
                _Invoice.Lines.BaseEntry     = invoice.OrderId;
                _Invoice.Lines.BaseLine      = 0;
            }

            if (_Invoice.Add() != 0)
            {
                transaction.Message = Company.GetLastErrorDescription();
            }
            else
            {
                Company.GetNewObjectCode(out newEntityId);
                transaction.Successfull(newEntityId);
            }

            Company.Disconnect();

            return(transaction);
        }
Пример #4
0
        private void CancelAllocationJE(int DocEntry)
        {
            SAPbobsCOM.Documents apCN = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oPurchaseCreditNotes);
            apCN.GetByKey(DocEntry);
            int totalCnt   = apCN.Lines.Count;
            int currentRow = 0;

            for (int i = 0; i < apCN.Lines.Count; i++)
            {
                currentRow++;
                apCN.Lines.SetCurrentLine(i);
                string AllocJE = apCN.Lines.UserFields.Fields.Item("U_AlocJe").Value.ToString();
                if (AllocJE != "")
                {
                    oApplication.StatusBar.SetText("Processing Allocation JE (" + currentRow.ToString() + " of " + totalCnt.ToString(), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);

                    postAllocationJERev(Convert.ToInt32(AllocJE), i, DocEntry);
                }
            }
        }
Пример #5
0
        public TransactionEntity Create(OrderEntity order, List <ItemEntity> items)
        {
            int               line        = 0;
            string            newEntityId = "";
            TransactionEntity transaction = new TransactionEntity();

            _Order            = Company.GetBusinessObject(BoObjectTypes.oOrders);
            _Order.CardCode   = order.CustomerCode;
            _Order.DocDueDate = order.OrderDueDate;

            foreach (ItemEntity item in items)
            {
                _Order.Lines.SetCurrentLine(line);
                _Order.Lines.WarehouseCode = item.WarehouseCode;
                _Order.Lines.ItemCode      = item.ItemCode;
                _Order.Lines.Quantity      = item.Quantity;
                _Order.Lines.UnitPrice     = item.UnitPrice;
                _Order.Lines.LineTotal     = item.LineTotal;
                _Order.Lines.TaxCode       = item.TaxCode;
                _Order.Lines.VatGroup      = item.VatGroup;
                _Order.Lines.Add();
                line += 1;
            }

            if (_Order.Add() != 0)
            {
                transaction.Message = Company.GetLastErrorDescription();
            }
            else
            {
                Company.GetNewObjectCode(out newEntityId);
                transaction.Successfull(newEntityId);
            }

            Company.Disconnect();

            return(transaction);
        }
Пример #6
0
        void IArmada_Sync.Add(string sKey, SAPbobsCOM.Company oCompany, string strLogger, string strWareHouse, string[] strValues, Hashtable htCCdet)
        {
            //Singleton.traceService("Has Record2");
            DataTable oHeader   = null;
            DataTable oDetails  = null;
            DataTable oPayments = null;

            SAPbobsCOM.Documents oInvoiceR = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oCreditNotes);
            SAPbobsCOM.Payments  oPayment  = (SAPbobsCOM.Payments)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oVendorPayments);

            try
            {
                string str_S_ORIN = "Exec Armada_Service_S_ORIN_s '" + sKey + "'";
                oDataSet = Singleton.objSqlDataAccess.ExecuteDataSet(str_S_ORIN, strLogger);

                if (oDataSet == null && oDataSet.Tables.Count == 0)
                {
                    return;
                }
                else
                {
                    oHeader   = oDataSet.Tables[0];
                    oDetails  = oDataSet.Tables[1];
                    oPayments = oDataSet.Tables[2];

                    if (oHeader != null && oHeader.Rows.Count > 0)
                    {
                        //Singleton.traceService("Has Record");
                        oInvoiceR.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items;

                        //Header Table
                        oInvoiceR.CardCode    = oHeader.Rows[0]["Code"].ToString();
                        oInvoiceR.CardName    = oHeader.Rows[0]["Name"].ToString();
                        oInvoiceR.DocDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                        oInvoiceR.NumAtCard   = oHeader.Rows[0]["DocNum"].ToString();
                        oInvoiceR.DocCurrency = oHeader.Rows[0]["DocCur"].ToString();

                        //oInvoice.DocRate = Convert.ToDouble(oHeader.Rows[0]["DocRate"].ToString());
                        oInvoiceR.Comments = oHeader.Rows[0]["Remarks"].ToString();
                        oInvoiceR.UserFields.Fields.Item("U_Z_PAYTYPE").Value = oHeader.Rows[0]["DocType"].ToString();
                        oInvoiceR.UserFields.Fields.Item("U_Z_CASHIER").Value = oHeader.Rows[0]["Cashier"].ToString();
                        oInvoiceR.UserFields.Fields.Item("U_Z_DOCTIME").Value = oHeader.Rows[0]["DocTime"].ToString();
                        oInvoiceR.UserFields.Fields.Item("U_Z_TrnNum").Value  = oHeader.Rows[0]["DocNum"].ToString();

                        if (oDetails.Rows.Count > 0)
                        {
                            foreach (DataRow dr in oDetails.Rows)
                            {
                                oInvoiceR.Lines.ItemCode        = dr["ItemCode"].ToString();
                                oInvoiceR.Lines.ItemDescription = dr["ItemDesc"].ToString();
                                oInvoiceR.Lines.Quantity        = Convert.ToDouble(dr["Qty"].ToString());
                                oInvoiceR.Lines.UnitPrice       = Convert.ToDouble(dr["UnitPrice"].ToString());
                                //oInvoice.Lines.Currency = dr["Currency"].ToString();
                                oInvoiceR.Lines.WarehouseCode = strWareHouse;
                                if (strValues[1] != "")
                                {
                                    oInvoiceR.Lines.CostingCode = strValues[1];
                                }
                                oInvoiceR.Lines.Add();
                            }
                        }
                        //oInvoice.DocTotal = Convert.ToDouble(oHeader.Rows[0]["DocTotal"].ToString());

                        if (oCompany.InTransaction)
                        {
                            oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                        }

                        oCompany.StartTransaction();

                        int intError = oInvoiceR.Add();
                        if (intError != 0)
                        {
                            //Singleton.traceService(intError.ToString());
                            Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), "0", "0", 0, intError.ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger);
                            if (oCompany.InTransaction)
                            {
                                oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                            }
                        }
                        else
                        {
                            //Singleton.traceService("Success");
                            string strDkey;
                            int    intDocNum = 0;
                            oCompany.GetNewObjectCode(out strDkey);
                            if (oInvoiceR.GetByKey(Convert.ToInt32(strDkey)))
                            {
                                intDocNum = oInvoiceR.DocNum;
                            }

                            //Singleton.traceService("Success2");

                            oPayment.CardCode    = oHeader.Rows[0]["Code"].ToString();
                            oPayment.DocType     = SAPbobsCOM.BoRcptTypes.rCustomer;
                            oPayment.DocDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                            oPayment.TaxDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                            oPayment.DocCurrency = oHeader.Rows[0]["DocCur"].ToString();
                            //Singleton.traceService("Success3");

                            oPayment.Invoices.DocEntry    = Convert.ToInt32(strDkey);
                            oPayment.Invoices.InvoiceType = SAPbobsCOM.BoRcptInvTypes.it_CredItnote;
                            oPayment.Invoices.SumApplied  = Convert.ToDouble(oHeader.Rows[0]["InvTotal"].ToString());
                            oPayment.Invoices.Add();

                            //Singleton.traceService("Success4");

                            if (oPayments.Rows.Count > 0)
                            {
                                foreach (DataRow dr in oPayments.Rows)
                                {
                                    //if (dr["PayMethod"].ToString() == "R")
                                    //{
                                    //    oPayment.CreditCards.CreditCard = 1;
                                    //    oPayment.CreditCards.CreditCardNumber = "1111";
                                    //    oPayment.CreditCards.CardValidUntil = System.DateTime.Now;
                                    //    oPayment.CreditCards.PaymentMethodCode = 1;
                                    //    oPayment.CreditCards.CreditSum = Convert.ToDouble(dr["PayAmount"].ToString());
                                    //    oPayment.CreditCards.VoucherNum = "1111";
                                    //    oPayment.CreditCards.Add();
                                    //    Singleton.traceService("Payment Credit");
                                    //}
                                    //else
                                    {
                                        oPayment.CashAccount = strValues[0].ToString();
                                        oPayment.CashSum     = Convert.ToDouble(dr["PayAmount"].ToString());
                                        //Singleton.traceService("Payment Cash");
                                    }
                                }
                            }

                            //Singleton.traceService("Payment Adding");
                            try
                            {
                                int intPayment = oPayment.Add();
                                if (intPayment == 0)
                                {
                                    //Singleton.traceService("Payment Successs");
                                    if (oCompany.InTransaction)
                                    {
                                        oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
                                    }
                                    Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger);
                                }
                                else
                                {
                                    //Singleton.traceService(intPayment.ToString());
                                    Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), "0", "0", 0, intPayment.ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger);
                                    if (oCompany.InTransaction)
                                    {
                                        oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (oCompany.InTransaction)
                                {
                                    oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                                }
                                Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger);
                if (oCompany.InTransaction)
                {
                    oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                }
                throw ex;
            }
            finally
            {
                oHeader  = null;
                oDetails = null;
                oDataSet = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oInvoiceR);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oPayment);
            }
        }
Пример #7
0
        public static string create_apinvoice_with_single_grnentry(int docentry, string invoice_number, SAPbobsCOM.Company oCompany)
        {
            var grpo      = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseDeliveryNotes);
            var apinvoice = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices);
            var recordset = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

            try
            {
                int iTotalPO_Line;
                if (grpo.GetByKey(docentry) == true)
                {
                    apinvoice.JournalMemo = TruncateLongString(invoice_number + '#' + apinvoice.CardName, 50);
                    apinvoice.DocDate     = DateTime.Now;
                    apinvoice.DocDueDate  = DateTime.Now;
                    apinvoice.NumAtCard   = TruncateLongString(invoice_number + '#' + apinvoice.CardName, 100);
                    apinvoice.Comments    = "Created by Ap Invoice Automation on " + DateTime.Now.ToShortDateString() + "";
                    iTotalPO_Line         = grpo.Lines.Count;

                    //Update GRPO Document
                    grpo.JournalMemo = TruncateLongString(invoice_number + '#' + apinvoice.CardName, 50);
                    grpo.Update();


                    int x;
                    for (x = 0; x <= iTotalPO_Line - 1; x++)
                    {
                        grpo.Lines.SetCurrentLine(x);

                        if (grpo.Lines.LineStatus == SAPbobsCOM.BoStatus.bost_Close)
                        {
                        }
                        else
                        {
                            apinvoice.Lines.ItemCode      = grpo.Lines.ItemCode;
                            apinvoice.Lines.WarehouseCode = grpo.Lines.WarehouseCode;
                            apinvoice.Lines.Quantity      = grpo.Lines.Quantity;
                            apinvoice.Lines.BaseType      = 20;
                            apinvoice.Lines.BaseEntry     = grpo.DocEntry;
                            apinvoice.Lines.BaseLine      = grpo.Lines.LineNum;
                            apinvoice.Lines.Add();
                        }
                    }
                }
                lErrCode = apinvoice.Add();
                if (lErrCode != 0)
                {
                    (oCompany).GetLastError(out lErrCode, out sErrMsg);
                }
            }

            catch (Exception Ex)
            {
                sErrMsg = Ex.ToString();
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(grpo);
                SAPbobsCOM.Documents documents = grpo = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(apinvoice);
                SAPbobsCOM.Documents documents1 = apinvoice = null;
                GC.Collect();
            }
            if (lErrCode == 0)
            {
                string strSql;
                strSql = "select DocNum from OPCH where DocNum= '" + Convert.ToString(((SAPbobsCOM.Company)oCompany).GetNewObjectKey()) + "'";
                recordset.DoQuery(strSql);
                return(Convert.ToString(recordset.Fields.Item("DocNum").Value));
            }
            else
            {
                return(sErrMsg);
            }
        }
Пример #8
0
        private int PostInspaction(string WOREntry, string itemCode, double Qty, string BSN, int startFrom)
        {
            int result = 0;

            try

            {
                string strUsrInfo = "SELECT * FROM \"@B1_QA_OUSR\" WHERE  \"Code\" = '" + oCompany.UserName + "' ";
                System.Data.DataTable dtUsrInfo = Program.objHrmsUI.getDataTable(strUsrInfo, "User Info");
                string prdWhs = "";
                if (dtUsrInfo != null && dtUsrInfo.Rows.Count > 0)
                {
                    prdWhs = dtUsrInfo.Rows[0]["U_PWHS"].ToString().Trim();
                }
                else
                {
                    oApplication.MessageBox("Inspaciton posting is not allowed for current user");
                    return(-1);
                }


                SAPbobsCOM.Items oitm = (SAPbobsCOM.Items)oCompany.GetBusinessObject(BoObjectTypes.oItems);
                oitm.GetByKey(itemCode);
                SAPbobsCOM.Documents InspactionGR = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oInventoryGenEntry);

                InspactionGR.DocDate = DateTime.Now.Date;
                InspactionGR.UserFields.Fields.Item("U_B1_QA_INSP_PN").Value = WOREntry;
                InspactionGR.Lines.ItemCode      = itemCode;
                InspactionGR.Lines.WarehouseCode = prdWhs;
                InspactionGR.Lines.AccountCode   = oitm.ExpanseAccount;
                InspactionGR.Lines.Quantity      = Qty;
                InspactionGR.Lines.Price         = 0.01;
                if (oitm.ManageBatchNumbers == BoYesNoEnum.tYES)
                {
                    InspactionGR.Lines.BatchNumbers.InternalSerialNumber = BSN;
                    InspactionGR.Lines.BatchNumbers.Quantity             = Qty;
                    InspactionGR.Lines.BatchNumbers.Add();
                }

                if (oitm.ManageSerialNumbers == BoYesNoEnum.tYES)
                {
                    double serQty = Qty;
                    while (serQty > 0)
                    {
                        InspactionGR.Lines.SerialNumbers.InternalSerialNumber = BSN + startFrom.ToString();
                        InspactionGR.Lines.SerialNumbers.Quantity             = 1;
                        InspactionGR.Lines.SerialNumbers.Add();
                        serQty--;
                        startFrom++;
                    }
                }
                InspactionGR.Comments = "Inspection GR";

                if (InspactionGR.Add() != 0)
                {
                    int    erroCode = 0;
                    string errDescr = "";
                    Program.objHrmsUI.oCompany.GetLastError(out erroCode, out errDescr);
                    oApplication.StatusBar.SetText("Failed send for inspaction  : " + errDescr);
                }
                else
                {
                    string outStr     = Convert.ToString(Program.objHrmsUI.oCompany.GetNewObjectKey());
                    string updateCall = "UPDATE OWOR set \"U_B1_QA_INSGR\"='" + outStr + "' WHERE \"DocEntry\" = '" + WOREntry.ToString() + "'";
                    result = Program.objHrmsUI.ExecQuery(updateCall, "Update Production Order");
                    oApplication.MessageBox("Inspaction Posted ");
                    oApplication.Menus.Item("1304").Activate();
                }
            }
            catch (Exception ex)
            {
                oApplication.MessageBox(ex.Message);
                result = -1;
            }

            return(result);
        }
Пример #9
0
        /// <summary>
        /// Funcion utilizada para mandar a SAP la información de la entrada de mercancia
        /// </summary>
        /// <returns></returns>
        public string funEnviarEntMercanciaSAP()
        {
            try
            {
                string mError = "";
                int    iError = 0;
                //Realizamos la conexion a SAP
                csAccesoDatos.proIniciarSesionSAP();
                //Verificamos si el documento ya se encuentra en SAP
                DataTable dtInventarioSAP = funVerificarEntInventarioSAP(DocNombre, CabNumero);
                //Si el documento se encuentra en SAP actualizamos la información de este en la informacion del animal
                if (dtInventarioSAP.Rows.Count > 0)
                {
                    //Recuperamos en las variables los valores de SAP
                    CabDocEntrySAPEntrada = int.Parse(dtInventarioSAP.Rows[0]["DocEntry"].ToString());
                    CabNumeroSAPEntrada   = int.Parse(dtInventarioSAP.Rows[0]["DocNum"].ToString());
                    //Actualizamos en el movimiento los datos de SAP
                    proActMovInventarioSalida(CabDocEntrySAPSalida, CabNumeroSAPSalida, CabCodigo);
                    return(mError);
                }
                else
                {
                    //Instanciamos la variable con el objeto de SAP Entrada de mercancias
                    SAPbobsCOM.Documents varOIGN = csConexionSap.objConexionSap.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenEntry);
                    //Recuperamos la informacion de la tabla de parametrizaciones para la activación del animal
                    int     varSerie           = clsSegDocumento.funRecNumSerieSAPEntrada(DocCodigo);                      //Serie
                    int     varCodMovimiento   = int.Parse(clsGenOpciones.CargarValor("G.Lab.Entrada.CodMov").ToString()); //Codigo movimiento
                    string  varNomMovimiento   = clsGenOpciones.CargarValor("G.Lab.Entrada.NomMov");                       //Movimientos
                    string  varComenDiario     = string.Format("Entrada laboratorio: {0}-{1}", DocNombre, CabNumero);      //Comentario, Comentario Diario
                    string  varCtaContable     = clsFinPlaCuenta.GetAcctCodeDeMovimiento(IteCodigo, varCodMovimiento);     //Cuenta contable
                    string  varIteTieLote      = clsInvItem.funRecTieLote(IteCodigo);                                      //Es gestionado por lote
                    decimal varCstAcumulado    = clsGraCstAcumulado.funRecValorCstAcumulado(AnmCodigo, "Bla");             //Costo acumulado
                    decimal varCstStdAcumulado = clsGraCstStdAcumulado.funRecValorCstStdAcumulado(AnmCodigo, "Bla");       //Costo standar acumulado
                    decimal varCstSalida       = funRecTotSalMercanciaSAP(CabDocEntrySAPSalida);
                    decimal varCstFormacion    = CabCstInicial + varCstAcumulado + varCstStdAcumulado + varCstSalida;
                    decimal varCosto           = decimal.Round(varCstFormacion / CabDosis, 4);
                    //Validamos si hay cuenta contable para el movimiento utilizado
                    if (string.IsNullOrEmpty(varCtaContable))
                    {
                        return("No se pudo obtener la cuenta contable para el movimiento de entrada");
                    }
                    //Datos de cabecera de la salida de mercancia SAP
                    varOIGN.Series           = varSerie;                                                                    //Serie
                    varOIGN.DocDate          = (DateTime)CabFecha;                                                          //Fecha de contabilización
                    varOIGN.TaxDate          = (DateTime)CabFecha;                                                          //Fecha de documento
                    varOIGN.Comments         = CabComentario;                                                               //Comentarios
                    varOIGN.JournalMemo      = varComenDiario;                                                              //Comentario asiento contable
                    varOIGN.PaymentGroupCode = -2;                                                                          //Lista de precios (Ultimo precio determinado)
                    //Valores del codigo y nombre del movimiento
                    varOIGN.UserFields.Fields.Item("U_Ita_codmovimiento").Value = varCodMovimiento;                         //Codigo movimiento
                    varOIGN.UserFields.Fields.Item("U_Ita_movimiento").Value    = varNomMovimiento;                         //Movimientos
                    //Valores de la auditoria del sistema umbrella
                    varOIGN.UserFields.Fields.Item("U_Ita_sysusuario").Value   = clsVariablesGlobales.varCodUsuario;        //Usuario del sistema umbrella
                    varOIGN.UserFields.Fields.Item("U_Ita_sysfecha").Value     = DateTime.Now.ToString("dd/MM/yyyy HH:mm"); //Fecha del sistema umbrella
                    varOIGN.UserFields.Fields.Item("U_Ita_sysip").Value        = clsVariablesGlobales.varIpMaquina;         //Ip del sistema umbrella
                    varOIGN.UserFields.Fields.Item("U_Ita_sysdocumento").Value = DocNombre;                                 //Codigo del documento
                    varOIGN.UserFields.Fields.Item("U_Ita_sysnumero").Value    = CabNumero.ToString();                      //Niumero del documento
                    //Datos de detalle de la salida de mercancia SAP
                    varOIGN.Lines.SetCurrentLine(0);
                    varOIGN.Lines.WarehouseCode   = BodCodigo;                                  //Almacen
                    varOIGN.Lines.ItemCode        = IteCodigo;                                  //Código
                    varOIGN.Lines.ItemDescription = IteNombre;                                  //Descripción
                    varOIGN.Lines.UserFields.Fields.Item("U_Ita_arete").Value = AnmAlternativo; //Arete
                    varOIGN.Lines.Quantity    = double.Parse(CabDosis.ToString());              //Cantidad
                    varOIGN.Lines.UnitPrice   = double.Parse(varCstFormacion.ToString());       //Costo
                    varOIGN.Lines.AccountCode = varCtaContable;                                 //Compensación de stocks reducir cuenta
                    //Verificamos si el item requiere lote
                    if (varIteTieLote.ToUpper().Equals("Y"))
                    {
                        varOIGN.Lines.BatchNumbers.SetCurrentLine(0);                                     //Nos posicionamos en la linea del lote recien creada
                        varOIGN.Lines.BatchNumbers.BatchNumber       = CabLote;                           //Lote
                        varOIGN.Lines.BatchNumbers.Quantity          = double.Parse(CabDosis.ToString()); //Cantidad lote
                        varOIGN.Lines.BatchNumbers.AddmisionDate     = (DateTime)CabFecha;                //Fecha de admisión
                        varOIGN.Lines.BatchNumbers.ManufacturingDate = (DateTime)CabFecha;                //Fecha de fabricación
                    }
                    iError = varOIGN.Add();
                    if (!iError.Equals(0))
                    {
                        csConexionSap.objConexionSap.GetLastError(out iError, out mError);
                        return(mError);
                    }
                    else
                    {
                        int varDocEntrySAPEntrada = 0;
                        int.TryParse(csConexionSap.objConexionSap.GetNewObjectKey().ToString(), out varDocEntrySAPEntrada);
                        varOIGN.GetByKey(varDocEntrySAPEntrada);
                        int varDocNumSAPEntrada = varOIGN.DocNum;

                        //Actualizamos en el movimiento los datos de SAP
                        proActMovInventarioEntrada(varDocEntrySAPEntrada, varDocNumSAPEntrada, CabCodigo);
                        //Actualizamos la depreciacion en el animal
                        clsGraAnimal.proActInfDepAcumulada(CabCstInicial, AnmCodigo);
                        return(mError);
                    }
                }
            }
            catch (Exception e) { throw new Exception(e.Message); }
            finally { csAccesoDatos.proFinalizarSesionSAP(); }
        }
Пример #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please wait...");
            DIApplication.DIConnect();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Connection successful");

            SAPbobsCOM.Documents lObjDocument = null;
            lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInvoices);

            var a = lObjDocument.GetByKey(185);
            var b = lObjDocument.GroupNumber;
            var c = lObjDocument.PaymentMethod;
            var d = lObjDocument.ExtraDays;
            var e = lObjDocument.PaymentGroupCode;

            ////SAPbobsCOM.JournalEntries lObjJournalEntries = null;
            //SAPbobsCOM.Documents lObjDocument = null;
            ////int lIntResult = -1;

            //try
            //{
            //    Console.WriteLine("Please wait...");
            //    DIApplication.DIConnect();
            //    Console.ForegroundColor = ConsoleColor.Yellow;
            //    Console.WriteLine("Connection successful");

            //    lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenExit);
            //    lObjDocument.HandWritten = SAPbobsCOM.BoYesNoEnum.tNO;
            //    lObjDocument.Series = 297;
            //    lObjDocument.DocDate = DateTime.Now;
            //    lObjDocument.DocDueDate = DateTime.Now;
            //    lObjDocument.Comments = "Salida de mercancías";
            //    lObjDocument.JournalMemo = "Salida de mercancías";

            //    lObjDocument.Lines.ItemCode = "A00000468";
            //    lObjDocument.Lines.WarehouseCode = "SUHEG";
            //    lObjDocument.Lines.Quantity = 20;

            //    lObjDocument.Lines.BatchNumbers.Quantity = 20;
            //    lObjDocument.Lines.BatchNumbers.BatchNumber = "Prueba161017_2";
            //    lObjDocument.Lines.BatchNumbers.Add();

            //    lObjDocument.Lines.Add();

            //    if (lObjDocument.Add() != 0)
            //    {
            //        Console.ForegroundColor = ConsoleColor.Red;
            //        Console.WriteLine(DIApplication.Company.GetLastErrorDescription());
            //    }


            //    //lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders);
            //    //lObjDocument.GetByKey(53);

            //    //if (lObjDocument != null)
            //    //{
            //    //    for (int i = 0; i < lObjDocument.Lines.Count; i++)
            //    //    {
            //    //        lObjDocument.Lines.SetCurrentLine(i);

            //    //        var a = lObjDocument.Lines.CostingCode;
            //    //        var b = lObjDocument.Lines.CostingCode2;
            //    //        var c = lObjDocument.Lines.CostingCode3;
            //    //        var d = lObjDocument.Lines.CostingCode4;
            //    //        var f = lObjDocument.Lines.CostingCode5;
            //    //    }
            //    //}


            //    //lObjJournalEntries = (SAPbobsCOM.JournalEntries)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oJournalEntries);
            //    //lObjJournalEntries.DueDate = DateTime.Today;
            //    //lObjJournalEntries.TaxDate = DateTime.Today;
            //    //lObjJournalEntries.AutoVAT = SAPbobsCOM.BoYesNoEnum.tYES;

            //    //lObjJournalEntries.Lines.AccountCode = "1070050001000";
            //    //lObjJournalEntries.Lines.ContraAccount = "2040010004000";
            //    //lObjJournalEntries.Lines.Credit = 0;
            //    //lObjJournalEntries.Lines.Debit = 100;
            //    //lObjJournalEntries.Lines.CostingCode = "SU_HERMO";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_GLO_Auxiliary").Value = "CL00000001";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_GLO_AuxType").Value = "1";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_SU_Folio").Value = "SU-HE-170001";
            //    //lObjJournalEntries.Lines.Add();

            //    //lObjJournalEntries.Lines.AccountCode = "2040010004000";
            //    //lObjJournalEntries.Lines.ContraAccount = "1070050001000";
            //    //lObjJournalEntries.Lines.Credit = 100;
            //    //lObjJournalEntries.Lines.Debit = 0;
            //    //lObjJournalEntries.Lines.CostingCode = "SU_HERMO";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_GLO_Auxiliary").Value = "CL00000002";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_GLO_AuxType").Value = "1";
            //    //lObjJournalEntries.Lines.UserFields.Fields.Item("U_SU_Folio").Value = "SU-HE-170001";
            //    //lObjJournalEntries.Lines.Add();

            //    //lIntResult = lObjJournalEntries.Add();

            //    //if (lIntResult != 0)
            //    //{
            //    //    Console.WriteLine(DIApplication.Company.GetLastErrorDescription());
            //    //}

            //    //DIApplication.Company.StartTransaction();
            //    //CreateDocument("62");
            //    //CreateDocument("63");
            //    //DIApplication.Company.EndTransaction(BoWfTransOpt.wf_RollBack);
            //}
            //catch (Exception lObjException)
            //{
            //    Console.ForegroundColor = ConsoleColor.Red;
            //    Console.WriteLine(lObjException.ToString());
            //}
            //finally
            //{
            //    //MemoryUtility.ReleaseComObject(lObjJournalEntries);
            //    MemoryUtility.ReleaseComObject(lObjDocument);
            //}

            Console.WriteLine("Please wait...");

            EntityFrameworkTransactionTest mObjTest = new EntityFrameworkTransactionTest();

            mObjTest.DoTest();

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
        }
Пример #11
0
        private void Outputs()
        {
            lObjErrorListDTO = new DTO.ErrorListDTO();
            int  lIntRetCode = 0;
            int  lIntSeries  = mObjRejectedDAO.GetSerieForOutputs(lIntUserSign);
            bool lBoolValid  = false;

            lObjGoodsIssues = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenExit);
            try
            {
                for (int i = 0; i < lListRejectedToInvoice.Count; i++)
                {
                    lObjErrorListDTO = new DTO.ErrorListDTO();
                    lStrReference    = lStrMainRWhs + "_" + lListRejectedToInvoice[i].Inspection;

                    if (CheckThreeDays(i) || HasInvoice(lStrReference, lListRejectedToInvoice[i].DistNumb))
                    {
                        lObjGoodsIssues.HandWritten = SAPbobsCOM.BoYesNoEnum.tNO;
                        lObjGoodsIssues.Series      = lIntSeries;
                        lObjGoodsIssues.UserFields.Fields.Item("U_MQ_OrigenFol").Value = lListRejectedToInvoice[i].Inspection;
                        lObjGoodsIssues.UserFields.Fields.Item("U_GLO_InMo").Value     = "S-GAN";
                        lObjGoodsIssues.DocDate    = DateTime.Today;
                        lObjGoodsIssues.DocDueDate = DateTime.Today;


                        lObjGoodsIssues.Lines.ItemCode      = lListRejectedToInvoice[i].HeadType;
                        lObjGoodsIssues.Lines.WarehouseCode = lStrMainRWhs;
                        lObjGoodsIssues.Lines.Quantity      = lListRejectedToInvoice[i].Quantity;

                        lObjGoodsIssues.Lines.BatchNumbers.BatchNumber = lListRejectedToInvoice[i].DistNumb;
                        lObjGoodsIssues.Lines.BatchNumbers.Quantity    = lListRejectedToInvoice[i].Quantity;

                        lObjGoodsIssues.Lines.BatchNumbers.Add();

                        lObjGoodsIssues.Lines.Add();

                        lIntRetCode = lObjGoodsIssues.Add();

                        if (lIntRetCode != 0)
                        {
                            string error = DIApplication.Company.GetLastErrorDescription();
                            Application.SBO_Application.StatusBar.SetText(error
                                                                          , SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                            lBoolValid = false;
                        }
                        else
                        {
                            lBoolValid = true;
                        }



                        if (lBoolValid == true)
                        {
                            lObjErrorListDTO.Option     = "CorrectOutput";
                            lObjErrorListDTO.Inspection = lListRejectedToInvoice[i].Inspection;
                            lObjlstErrorDTO.Add(lObjErrorListDTO);
                        }
                    }
                    else
                    {
                        lObjErrorListDTO.Option     = "OutOfTime";
                        lObjErrorListDTO.Inspection = lListRejectedToInvoice[i].Inspection.ToString();

                        lObjlstErrorDTO.Add(lObjErrorListDTO);
                    }
                }
            }
            catch (Exception lObjException)
            {
                throw new DAOException(lObjException.Message, lObjException);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjGoodsIssues);
            }
        }
Пример #12
0
        private void postAllocationJE(int invEntry)
        {
            try
            {
                SAPbobsCOM.Documents      apInv = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oPurchaseInvoices);
                SAPbobsCOM.JournalEntries apJE  = (SAPbobsCOM.JournalEntries)oCompany.GetBusinessObject(BoObjectTypes.oJournalEntries);
                SAPbobsCOM.JournalEntries AllocationJE;
                apInv.GetByKey(invEntry);
                int ApJeNum = apInv.TransNum;
                apJE.GetByKey(ApJeNum);

                System.Data.DataTable dtCandidateRows = new System.Data.DataTable();

                dtCandidateRows.Columns.Add("LineNum");
                dtCandidateRows.Columns.Add("AlocCode");
                dtCandidateRows.Columns.Add("GLCode");
                dtCandidateRows.Columns.Add("Amount");
                dtCandidateRows.Columns.Add("DR");


                for (int i = 0; i < apInv.Lines.Count; i++)
                {
                    apInv.Lines.SetCurrentLine(i);
                    if (apInv.Lines.UserFields.Fields.Item("U_CostCode").Value.ToString().Trim() != "" && (apInv.Lines.UserFields.Fields.Item("U_AlocJe").Value.ToString().Trim() == "0" || apInv.Lines.UserFields.Fields.Item("U_AlocJe").Value.ToString().Trim() == ""))
                    {
                        dtCandidateRows.Rows.Add(i, apInv.Lines.UserFields.Fields.Item("U_CostCode").Value.ToString().Trim(), apInv.Lines.AccountCode, (apInv.Lines.LineTotal), apInv.Lines.CostingCode);
                    }
                }

                int totalCnt   = dtCandidateRows.Rows.Count;
                int currentRow = 0;
                foreach (DataRow dr in dtCandidateRows.Rows)
                {
                    currentRow++;
                    oApplication.StatusBar.SetText("Processing Allocation JE (" + currentRow.ToString() + " of " + totalCnt.ToString(), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                    string costCode = dr["AlocCode"].ToString();

                    Hashtable hp = new Hashtable();
                    hp.Add("~p1", costCode);



                    string strRulCode = Program.objHrmsUI.getQryString("141_GET_001", hp); //"select t1.U_AR from [@B1_DBOQD] t0 inner join [@B1_IBOQ] t1 on t0.U_ItemCode = t1.Code where t0.Code = '~p1' ";


                    System.Data.DataTable dtRuleCode = Program.objHrmsUI.getDataTable(strRulCode, "Getting RuleCode");
                    if (dtRuleCode == null || dtRuleCode.Rows.Count == 0)
                    {
                        oApplication.MessageBox("Cost Code not associated with Indirect BOQ to post allocaiton JE");
                        continue;
                    }

                    string allocationCode = dtRuleCode.Rows[0]["U_AR"].ToString();


                    string CreditGLCode = dr["GLCode"].ToString();
                    double CreditAmount = Convert.ToDouble(dr["Amount"]);
                    int    lineNum      = Convert.ToInt32(dr["LineNum"]);
                    string DR           = dr["DR"].ToString();
                    hp.Clear();
                    hp.Add("~p1", allocationCode);


                    string strDetails            = Program.objHrmsUI.getQryString("141_GET_002", hp);// @"Select t0.U_AP as AP , t1.U_AcctCode,t1.Code, t3.[U_BU] as BaseOn ,isnull(t1.U_FACode,'') as FA from [@B1_ARD] t0 inner join [@B1_AM] t1 on t1.Code = t0.U_CMC  inner join [@B1_AR] t3 on t3.[Code]=t0.[U_RuleCode] where t0.U_RuleCode='~p1'";
                    System.Data.DataTable dtrule = Program.objHrmsUI.getDataTable(strDetails, "Getting Rule Detail");
                    if (dtrule.Rows.Count > 0)
                    {
                        AllocationJE           = (SAPbobsCOM.JournalEntries)oCompany.GetBusinessObject(BoObjectTypes.oJournalEntries);
                        AllocationJE.Reference = allocationCode;

                        double debitTotal = 0.00;
                        foreach (DataRow drDetails in dtrule.Rows)
                        {
                            string debitAccount = drDetails["U_AcctCode"].ToString();
                            double AP           = Convert.ToDouble(drDetails["AP"]);
                            double debitAmount  = CreditAmount * AP / 100.00000;
                            string baseOn       = Convert.ToString(drDetails["BaseOn"]);
                            string FA           = Convert.ToString(drDetails["FA"]);
                            addChildJeLines(AllocationJE, drDetails["Code"].ToString(), debitAmount, debitAccount, baseOn, FA, costCode, AP.ToString());
                        }

                        for (int k = 0; k < AllocationJE.Lines.Count; k++)
                        {
                            AllocationJE.Lines.SetCurrentLine(k);
                            debitTotal += AllocationJE.Lines.Debit;
                        }

                        AllocationJE.Lines.AccountCode = CreditGLCode;
                        //  AllocationJE.Lines.Credit = debitTotal;
                        AllocationJE.Lines.Credit      = CreditAmount;
                        AllocationJE.Lines.Reference1  = allocationCode;
                        AllocationJE.Lines.CostingCode = DR;
                        AllocationJE.Lines.Add();



                        double diffAmount = CreditAmount - debitTotal;

                        if (CreditAmount != debitTotal)
                        {
                            string roundAcct = getRoundingAcct();
                            AllocationJE.Lines.AccountCode = roundAcct;

                            AllocationJE.Lines.Debit      = diffAmount;
                            AllocationJE.Lines.Reference1 = allocationCode;
                            //  AllocationJE.Lines.CostingCode = DR;
                            AllocationJE.Lines.Add();
                        }



                        if (AllocationJE.Add() != 0)
                        {
                            int    erroCode = 0;
                            string errDescr = "";
                            Program.objHrmsUI.oCompany.GetLastError(out erroCode, out errDescr);
                            oApplication.StatusBar.SetText("Failed to add Order  : " + errDescr);
                        }
                        else
                        {
                            string outStr = Convert.ToString(Program.objHrmsUI.oCompany.GetNewObjectKey());

                            hp.Clear();
                            hp.Add("~p1", outStr);
                            hp.Add("~p2", invEntry);
                            hp.Add("~p3", lineNum);

                            string updateCall = Program.objHrmsUI.getQryString("141_CRUD_001", hp);// "Update pch1 set U_AlocJE='~p1' where docentry = '~p2' and linenum='~p3'";
                            int    result     = Program.objHrmsUI.ExecQuery(updateCall, "Update Line JE");

                            oApplication.Menus.Item("1304").Activate();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                oApplication.MessageBox(ex.Message);
            }
        }
Пример #13
0
        void IArmada_Sync.Add(string sKey, SAPbobsCOM.Company oCompany, string strLogger, string strWareHouse, string[] strValues, Hashtable htCCdet)
        {
            //Singleton.traceService("Has Record2");
            DataTable oHeader  = null;
            DataTable oDetails = null;

            SAPbobsCOM.Documents oGRPO = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oPurchaseDeliveryNotes);

            try
            {
                string str_S_OPDN = "Exec Armada_Service_S_OPDN_s '" + sKey + "'";
                oDataSet = Singleton.objSqlDataAccess.ExecuteDataSet(str_S_OPDN, strLogger);

                if (oDataSet == null && oDataSet.Tables.Count == 0)
                {
                    return;
                }
                else
                {
                    oHeader  = oDataSet.Tables[0];
                    oDetails = oDataSet.Tables[1];

                    if (oHeader != null && oHeader.Rows.Count > 0)
                    {
                        //Singleton.traceService("Has Record");
                        oGRPO.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items;

                        //Header Table
                        oGRPO.CardCode        = oHeader.Rows[0]["VCode"].ToString();
                        oGRPO.CardName        = oHeader.Rows[0]["VName"].ToString();
                        oGRPO.DocDate         = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                        oGRPO.NumAtCard       = oHeader.Rows[0]["DocNum"].ToString();
                        oGRPO.DocCurrency     = oHeader.Rows[0]["DocCur"].ToString();
                        oGRPO.Comments        = oHeader.Rows[0]["Remarks"].ToString();
                        oGRPO.DiscountPercent = Convert.ToDouble(oHeader.Rows[0]["DiscPrct"].ToString());
                        oGRPO.UserFields.Fields.Item("U_Z_TrnNum").Value = oHeader.Rows[0]["DocNum"].ToString();

                        if (oDetails.Rows.Count > 0)
                        {
                            foreach (DataRow dr in oDetails.Rows)
                            {
                                oGRPO.Lines.ItemCode        = dr["ItemCode"].ToString();
                                oGRPO.Lines.ItemDescription = dr["ItemDesc"].ToString();
                                oGRPO.Lines.Quantity        = Convert.ToDouble(dr["Qty"].ToString());
                                oGRPO.Lines.UnitPrice       = Convert.ToDouble(dr["UnitPrice"].ToString());
                                oGRPO.Lines.BaseType        = 18;
                                oGRPO.Lines.BaseEntry       = Convert.ToInt32(dr["BaseEntry"].ToString());
                                oGRPO.Lines.BaseLine        = Convert.ToInt32(dr["BaseLine"].ToString());
                                oGRPO.Lines.WarehouseCode   = strWareHouse;
                                oGRPO.Lines.Add();
                            }
                        }
                        //oInvoice.DocTotal = Convert.ToDouble(oHeader.Rows[0]["DocTotal"].ToString());

                        int intError = oGRPO.Add();
                        if (intError != 0)
                        {
                            //Singleton.traceService(intError.ToString());
                            Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.GRPO.ToString(), "0", "0", 0, intError.ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger);
                        }
                        else
                        {
                            //Singleton.traceService("Success");
                            string strDkey;
                            int    intDocNum = 0;
                            oCompany.GetNewObjectCode(out strDkey);
                            if (oGRPO.GetByKey(Convert.ToInt32(strDkey)))
                            {
                                intDocNum = oGRPO.DocNum;
                            }

                            //Singleton.traceService("Payment Successs");
                            Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.GRPO.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARCreditMemo.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger);
                throw ex;
            }
            finally
            {
                oHeader  = null;
                oDetails = null;
                oDataSet = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oGRPO);
            }
        }
Пример #14
0
        void IArmada_Sync.Add(string sKey, SAPbobsCOM.Company oCompany, string strLogger, string strWareHouse, string[] strValues, Hashtable htCCdet)
        {
            DataTable oHeader   = null;
            DataTable oDetails  = null;
            DataTable oPayments = null;

            SAPbobsCOM.Documents oInvoice = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oInvoices);
            SAPbobsCOM.Payments  oPayment = (SAPbobsCOM.Payments)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oIncomingPayments);

            try
            {
                string str_S_OINV = "Exec Armada_Service_S_OINV_s '" + sKey + "'";
                traceService("Query :" + str_S_OINV);
                oDataSet = Singleton.objSqlDataAccess.ExecuteDataSet(str_S_OINV, strLogger);

                if (oDataSet == null && oDataSet.Tables.Count == 0)
                {
                    return;
                }
                else
                {
                    oHeader   = oDataSet.Tables[0];
                    oDetails  = oDataSet.Tables[1];
                    oPayments = oDataSet.Tables[2];
                    traceService("Adding HASRCROD");

                    if (oHeader != null && oHeader.Rows.Count > 0)
                    {
                        traceService("Adding INvoice");
                        oInvoice.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items;

                        //Header Table
                        oInvoice.CardCode    = oHeader.Rows[0]["Code"].ToString();
                        oInvoice.CardName    = oHeader.Rows[0]["Name"].ToString();
                        oInvoice.DocDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                        oInvoice.NumAtCard   = oHeader.Rows[0]["DocNum"].ToString();
                        oInvoice.DocCurrency = oHeader.Rows[0]["DocCur"].ToString();
                        //oInvoice.DocRate = Convert.ToDouble(oHeader.Rows[0]["DocRate"].ToString());
                        oInvoice.Comments        = oHeader.Rows[0]["Remarks"].ToString();
                        oInvoice.DiscountPercent = Convert.ToDouble(oHeader.Rows[0]["DisPrct"].ToString());
                        oInvoice.UserFields.Fields.Item("U_Z_PAYTYPE").Value = oHeader.Rows[0]["DocType"].ToString();
                        oInvoice.UserFields.Fields.Item("U_Z_CASHIER").Value = oHeader.Rows[0]["Cashier"].ToString();
                        oInvoice.UserFields.Fields.Item("U_Z_DOCTIME").Value = oHeader.Rows[0]["DocTime"].ToString();
                        oInvoice.UserFields.Fields.Item("U_Z_TrnNum").Value  = oHeader.Rows[0]["DocNum"].ToString();

                        if (oDetails.Rows.Count > 0)
                        {
                            traceService("Adding Details");
                            foreach (DataRow dr in oDetails.Rows)
                            {
                                oInvoice.Lines.ItemCode        = dr["ItemCode"].ToString();
                                oInvoice.Lines.ItemDescription = dr["ItemDesc"].ToString();
                                oInvoice.Lines.Quantity        = Convert.ToDouble(dr["Qty"].ToString());
                                oInvoice.Lines.UnitPrice       = Convert.ToDouble(dr["UnitPrice"].ToString());
                                //oInvoice.Lines.Currency = dr["Currency"].ToString();
                                oInvoice.Lines.WarehouseCode = strWareHouse;
                                if (strValues[0] != "")
                                {
                                    oInvoice.Lines.CostingCode = strValues[0];
                                }
                                oInvoice.Lines.Add();
                            }
                            traceService("Details Added");
                        }
                        //oInvoice.DocTotal = Convert.ToDouble(oHeader.Rows[0]["DocTotal"].ToString());

                        if (oCompany.InTransaction)
                        {
                            oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                        }


                        oCompany.StartTransaction();

                        int intError = oInvoice.Add();
                        if (intError != 0)
                        {
                            traceService(oCompany.GetLastErrorDescription());

                            if (oCompany.InTransaction)
                            {
                                oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                            }

                            Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARInvoice.ToString(), "0", "0", 0, oCompany.GetLastErrorCode().ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger);
                        }
                        else
                        {
                            string strDkey;
                            int    intDocNum = 0;
                            oCompany.GetNewObjectCode(out strDkey);

                            if (oInvoice.GetByKey(Convert.ToInt32(strDkey)))
                            {
                                intDocNum = oInvoice.DocNum;
                            }

                            if (oHeader.Rows[0]["DocType"].ToString() == "P")
                            {
                                oPayment.CardCode    = oHeader.Rows[0]["Code"].ToString();
                                oPayment.DocType     = SAPbobsCOM.BoRcptTypes.rCustomer;
                                oPayment.DocDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                                oPayment.TaxDate     = Convert.ToDateTime(oHeader.Rows[0]["DocDate"].ToString());
                                oPayment.DocCurrency = oHeader.Rows[0]["DocCur"].ToString();

                                oPayment.Invoices.DocEntry    = Convert.ToInt32(strDkey);
                                oPayment.Invoices.InvoiceType = SAPbobsCOM.BoRcptInvTypes.it_Invoice;
                                oPayment.Invoices.SumApplied  = Convert.ToDouble(oHeader.Rows[0]["InvTotal"].ToString());
                                oPayment.Invoices.Add();

                                if (oPayments.Rows.Count > 0)
                                {
                                    foreach (DataRow dr in oPayments.Rows)
                                    {
                                        if (dr["PayMethod"].ToString() == "R")
                                        {
                                            DataRow ccRows = (DataRow)htCCdet[dr["CardType"].ToString()];
                                            if (ccRows != null)
                                            {
                                                oPayment.CreditCards.CreditCard        = Convert.ToInt16(ccRows["U_CREDITCARD"].ToString());
                                                oPayment.CreditCards.CreditCardNumber  = (ccRows["U_CARDNUMBER"].ToString());
                                                oPayment.CreditCards.CardValidUntil    = Convert.ToDateTime(ccRows["U_CARDVALID"].ToString());
                                                oPayment.CreditCards.PaymentMethodCode = Convert.ToInt16(ccRows["U_PAYMENTMETHOD"].ToString());
                                                oPayment.CreditCards.CreditSum         = Convert.ToDouble(dr["PayAmount"].ToString());
                                                oPayment.CreditCards.VoucherNum        = "1111";
                                                oPayment.CreditCards.Add();
                                            }
                                        }
                                        else
                                        {
                                            oPayment.CashSum = Convert.ToDouble(dr["PayAmount"].ToString());
                                        }
                                    }
                                }

                                int intPayment = oPayment.Add();
                                if (intPayment == 0)
                                {
                                    if (oCompany.InTransaction)
                                    {
                                        oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
                                    }

                                    traceService("Commited");
                                    Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARInvoice.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger);
                                    traceService("Commited Completed..");
                                }
                                else
                                {
                                    Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARInvoice.ToString(), "0", "0", 0, oCompany.GetLastErrorCode().ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger);
                                    if (oCompany.InTransaction)
                                    {
                                        oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                                    }
                                }
                            }
                            else
                            {
                                if (oCompany.InTransaction)
                                {
                                    oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
                                }

                                traceService("Commited1");
                                Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARInvoice.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger);
                                traceService("Commited Completed..1");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.ARInvoice.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger);
                if (oCompany.InTransaction)
                {
                    oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                }
                traceService("Error 1 : " + ex.Message);
                throw ex;
            }
            finally
            {
                oHeader  = null;
                oDetails = null;
                oDataSet = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oInvoice);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oPayment);
            }
        }
Пример #15
0
        private void updateInvoice()
        {
            int k = dtDetail.Rows.Count;

            Hashtable oldDelWhs = new Hashtable(), oldTypeCode = new Hashtable(), oldPickWhs = new Hashtable();

            for (int i = 0; i < k; i++)
            {
                oldDelWhs.Add(i, Convert.ToString(dtDetail.GetValue("DelWhs", i)));
                oldTypeCode.Add(i, Convert.ToString(dtDetail.GetValue("TypeCode", i)));
                oldPickWhs.Add(i, Convert.ToString(dtDetail.GetValue("PickWhs", i)));
            }
            mtDet.FlushToDataSource();

            //if (!validateinput())
            //{
            //    return;
            //}


            string DIERror = "";


            string updatShipDate = "";

            for (int i = 0; i < k; i++)
            {
                DateTime ndelDate = Convert.ToDateTime(dtDetail.GetValue("nDelDate", i));
                DateTime deldate  = Convert.ToDateTime(dtDetail.GetValue("DelDate", i));
                if (ndelDate != deldate)
                {
                    if (ndelDate < DateTime.Now.Date)
                    {
                        oApplication.SetStatusBarMessage("Old Delivery Date for Line : " + (i + 1).ToString());
                        return;
                    }
                }
            }


            updatShipDate = "";
            for (int i = 0; i < k; i++)
            {
                // updatShipDate += "Update inv1  set shipdate='" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "', FreeTxt = 'what reading'   where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";

                string PickDate  = Convert.ToString(dtDetail.GetValue("nPickDate", i));
                string PickShift = dtDetail.GetValue("nPickShift", i);
                if (PickDate != "" && PickShift != "")
                {
                    updatShipDate += "Update inv1 set U_DelTypCd = '" + Convert.ToString(dtDetail.GetValue("TypeCode", i)) + "' ,  shipdate='" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "' , U_DelShift='" + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "',";
                    updatShipDate += "  U_DeliveryWH ='" + Convert.ToString(dtDetail.GetValue("DelWhs", i)) + "',U_PickingWh='" + Convert.ToString(dtDetail.GetValue("PickWhs", i)) + "' , U_PickShift ='" + Convert.ToString(dtDetail.GetValue("nPickShift", i)) + "' , u_PickDate = '" + Convert.ToString(dtDetail.GetValue("nPickDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                }
                else
                {
                    updatShipDate += "Update inv1 set  U_DelTypCd = '" + Convert.ToString(dtDetail.GetValue("TypeCode", i)) + "' , shipdate='" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "' , U_DeliveryWH ='" + Convert.ToString(dtDetail.GetValue("DelWhs", i)) + "',U_PickingWh='" + Convert.ToString(dtDetail.GetValue("PickWhs", i)) + "' ,  U_DelShift='" + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "' where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                }
            }


            Program.objHrmsUI.ExecQuery(updatShipDate, "Temp Update Ship Date");


            try
            {
                SAPbobsCOM.Documents ARInv = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInvoices);
                ARInv.GetByKey(Convert.ToInt32(Convert.ToString(dtDetail.GetValue("DocEntry", 0))));

                for (int i = 0; i < k; i++)
                {
                    int lineNum = Convert.ToInt32(Convert.ToString(dtDetail.GetValue("LineNum", i)));
                    ARInv.Lines.SetCurrentLine(i);
                    try
                    {
                        // ARInv.Lines.ShipDate = Convert.ToDateTime(dtDetail.GetValue("nDelDate", i));
                        ARInv.Lines.UserFields.Fields.Item("U_DelTypCd").Value   = Convert.ToString(dtDetail.GetValue("TypeCode", i));
                        ARInv.Lines.UserFields.Fields.Item("U_DelShift").Value   = Convert.ToString(dtDetail.GetValue("nDelShift", i));
                        ARInv.Lines.UserFields.Fields.Item("U_DeliveryWH").Value = Convert.ToString(dtDetail.GetValue("DelWhs", i));
                        ARInv.Lines.UserFields.Fields.Item("U_PickingWh").Value  = Convert.ToString(dtDetail.GetValue("PickWhs", i));
                        ARInv.Lines.UserFields.Fields.Item("U_PickShift").Value  = Convert.ToString(dtDetail.GetValue("nPickShift", i));
                        if (Convert.ToString(dtDetail.GetValue("nPickDate", i)) != "")
                        {
                            ARInv.Lines.UserFields.Fields.Item("U_PickDate").Value = Convert.ToDateTime(dtDetail.GetValue("nPickDate", i));
                        }
                        else
                        {
                            ARInv.Lines.UserFields.Fields.Item("U_PickDate").Value = "";
                        }
                        //   ARInv.Lines.FreeText = "What Reaching";
                        //     ARInv.Lines.SetCurrentLine(lineNum);
                    }
                    catch (Exception ex)
                    {
                        oApplication.SetStatusBarMessage("Assigning Values : " + ex.Message);
                        DIERror += "Assignment Error : " + ex.Message;
                    }
                }
                int result = 0;
                result = ARInv.Update();
                if (result != 0)
                {
                    int    errorCode = 0;
                    string errmsg    = "";
                    oCompany.GetLastError(out errorCode, out errmsg);
                    oApplication.SetStatusBarMessage(errmsg);
                    DIERror      += errmsg;
                    updatShipDate = "";
                    for (int i = 0; i < k; i++)
                    {
                        // updatShipDate += "Update inv1  set shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";


                        string PickDate  = Convert.ToString(dtDetail.GetValue("nPickDate", i));
                        string PickShift = dtDetail.GetValue("nPickShift", i);
                        if (PickDate != "" && PickShift != "")
                        {
                            updatShipDate += "Update inv1 set U_DelTypCd = '" + oldTypeCode[i].ToString() + "' ,  shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "' , U_DelShift='" + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "',";
                            updatShipDate += "  U_DeliveryWH ='" + oldDelWhs[i].ToString() + "',U_PickingWh='" + oldPickWhs[i].ToString() + "' , U_PickShift ='" + Convert.ToString(dtDetail.GetValue("PickShift", i)) + "' , u_PickDate = '" + Convert.ToString(dtDetail.GetValue("PickDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                        }
                        else
                        {
                            updatShipDate += "Update inv1 set  U_DelTypCd = '" + oldTypeCode[i].ToString() + "' , shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "' , U_DeliveryWH ='" + oldDelWhs[i].ToString() + "',U_PickingWh='" + oldPickWhs[i].ToString() + "' ,  U_DelShift='" + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "' where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                        }
                    }
                    Program.objHrmsUI.ExecQuery(updatShipDate, "Temp Update Ship Date");
                }
                else
                {
                    for (int i = 0; i < k; i++)
                    {
                        string oinvHeader = "";

                        oinvHeader += " update oinv set header = isnull( convert(varchar,header),'')  + ' Schedule Updated for  " + Convert.ToString(dtDetail.GetValue("LineNum", i)) + " -" + Convert.ToString(dtDetail.GetValue("ItemCode", i)) + ". Old Values (" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "," + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "," + Convert.ToString(dtDetail.GetValue("PickDate", i)) + "," + Convert.ToString(dtDetail.GetValue("PickShift", i)) + ") ";
                        oinvHeader += "  New Values (" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "," + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "," + Convert.ToString(dtDetail.GetValue("nPickDate", i)) + "," + Convert.ToString(dtDetail.GetValue("nPickShift", i)) + ") ' where docentry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' ";

                        Program.objHrmsUI.ExecQuery(oinvHeader, "Updating Remarks");
                    }
                }
            }
            catch (Exception ex)
            {
                DIERror = ex.Message;

                oApplication.SetStatusBarMessage("General Error !" + ex.Message + " Known Error " + DIERror, BoMessageTime.bmt_Short, false);
                updatShipDate = "";
                for (int i = 0; i < k; i++)
                {
                    // updatShipDate += "Update inv1  set shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ; ";
                    string PickDate  = Convert.ToString(dtDetail.GetValue("nPickDate", i));
                    string PickShift = dtDetail.GetValue("nPickShift", i);
                    if (PickDate != "" && PickShift != "")
                    {
                        updatShipDate += "Update inv1 set U_DelTypCd = '" + oldTypeCode[i].ToString() + "' ,  shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "' , U_DelShift='" + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "',";
                        updatShipDate += "  U_DeliveryWH ='" + oldDelWhs[i].ToString() + "',U_PickingWh='" + oldPickWhs[i].ToString() + "' , U_PickShift ='" + Convert.ToString(dtDetail.GetValue("PickShift", i)) + "' , u_PickDate = '" + Convert.ToString(dtDetail.GetValue("PickDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                    }
                    else
                    {
                        updatShipDate += "Update inv1 set  U_DelTypCd = '" + oldTypeCode[i].ToString() + "' , shipdate='" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "' , U_DeliveryWH ='" + oldDelWhs[i].ToString() + "',U_PickingWh='" + oldPickWhs[i].ToString() + "' ,  U_DelShift='" + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "' where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ;";
                    }
                }
                Program.objHrmsUI.ExecQuery(updatShipDate, "Temp Update Ship Date");
            }



            //// Old Code ///

            /*
             * if (!validateinput())
             * {
             *  return;
             * }
             * int k = dtDetail.Rows.Count;
             * for (int i = 0; i < k; i++)
             * {
             *  string updateLine="";
             *  string oinvHeader = "";
             *  string PickDate = Convert.ToString( dtDetail.GetValue("nPickShift",i));
             *  string PickShift = dtDetail.GetValue("nPickShift",i);
             *  if(PickDate !="" && PickShift!="")
             *  {
             *      updateLine = "Update inv1 set U_DelTypCd = '" + Convert.ToString(dtDetail.GetValue("TypeCode", i)) + "' ,  shipdate='" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "' , U_DelShift='" + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "',";
             *      updateLine += "  U_DeliveryWH ='" + Convert.ToString(dtDetail.GetValue("DelWhs", i)) + "',U_PickingWh='" + Convert.ToString(dtDetail.GetValue("PickWhs", i)) + "' , U_PickShift ='" + Convert.ToString(dtDetail.GetValue("nPickShift", i)) + "' , u_PickDate = '" + Convert.ToString(dtDetail.GetValue("nPickDate", i)) + "'  where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ";
             *
             *  }
             *  else
             *  {
             *      updateLine = "Update inv1 set  U_DelTypCd = '" + Convert.ToString(dtDetail.GetValue("TypeCode", i)) + "' , shipdate='" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "' , U_DeliveryWH ='" + Convert.ToString(dtDetail.GetValue("DelWhs", i)) + "',U_PickingWh='" + Convert.ToString(dtDetail.GetValue("PickWhs", i)) + "' ,  U_DelShift='" + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "' where DocEntry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' and linenum='" + Convert.ToString(dtDetail.GetValue("LineNum", i)) + "' ";
             *  }
             *  oinvHeader += " update oinv set header = isnull( convert(varchar,header),'')  + ' Schedule Updated for  " + Convert.ToString(dtDetail.GetValue("LineNum", i)) + " -" + Convert.ToString(dtDetail.GetValue("ItemCode", i)) + ". Old Values (" + Convert.ToString(dtDetail.GetValue("DelDate", i)) + "," + Convert.ToString(dtDetail.GetValue("DelShift", i)) + "," + Convert.ToString(dtDetail.GetValue("PickDate", i)) + "," + Convert.ToString(dtDetail.GetValue("PickShift", i)) + ") ";
             *  oinvHeader += "  New Values (" + Convert.ToString(dtDetail.GetValue("nDelDate", i)) + "," + Convert.ToString(dtDetail.GetValue("nDelShift", i)) + "," + Convert.ToString(dtDetail.GetValue("nPickDate", i)) + "," + Convert.ToString(dtDetail.GetValue("nPickShift", i)) + ") ' where docentry = '" + Convert.ToString(dtDetail.GetValue("DocEntry", i)) + "' ";
             *
             *  Program.objHrmsUI.ExecQuery(updateLine, "Updating Schedule");
             *  Program.objHrmsUI.ExecQuery(oinvHeader, "Updating Remarks");
             *
             *
             *
             * }
             *
             *
             *
             *//// old Code Ended


            //    oApplication.SetStatusBarMessage("Schedule Updated Successfully!", BoMessageTime.bmt_Short, false);
            if (DIERror == "")
            {
                oApplication.SetStatusBarMessage("Schedule Updated Successfully!", BoMessageTime.bmt_Short, false);
                loadInvoice();
            }
        }
Пример #16
0
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                //Instanciamos la clase oFactura de tipo Documents, en los parametros dfinimos el tipo de objeto oPurchaseInvoice

                //para trabajar con preliminares
                SAPbobsCOM.Documents oPedido = (SAPbobsCOM.Documents)oEmpresa.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
                oPedido.DocObjectCode = SAPbobsCOM.BoObjectTypes.oOrders;

                //SAPbobsCOM.Documents oPedido = oEmpresa.GetBusinessObject(BoObjectTypes.oOrders);


                //oPO.CardCode = "V10000";
                //ENCABEZADO DE LA FACTURA
                oPedido.Series = 0;

                oPedido.CardCode   = TxtCodCliente.Text;
                oPedido.DocType    = BoDocumentTypes.dDocument_Items;
                oPedido.DocDueDate = DatePickerEntrega.Value;
                //----------

                //oPedido.HandWritten = tNO;
                //oPedido.PaymentGroupCode = -1;

                //-----

                oPedido.DocDate = DatePickerFecha.Value;
                //oPedido.TaxDate = DatePickTax.Value;
                oPedido.NumAtCard       = TxtOC.Text;
                oPedido.Comments        = TxtComentario.Text;
                oPedido.SalesPersonCode = 15;
                oPedido.UserFields.Fields.Item("U_AutCreditos").Value = "FV-LM";



                //DETALLE DE LA FACTURA
                for (int i = 0; i <= DgvDetalle.RowCount - 2; i++)

                {
                    //oPedido.Lines.SetCurrentLine(i);

                    //oPedido.Lines.SetCurrentLine(i);
                    //oPedido.Lines.Quantity = 1;
                    oPedido.Lines.Quantity      = double.Parse(DgvDetalle.Rows[i].Cells[0].Value.ToString());
                    oPedido.Lines.PriceAfterVAT = double.Parse(DgvDetalle.Rows[i].Cells[4].Value.ToString());


                    oPedido.Lines.ItemDescription = DgvDetalle.Rows[i].Cells[1].Value.ToString();
                    oPedido.Lines.ItemCode        = DgvDetalle.Rows[i].Cells[2].Value.ToString();

                    //oPedido.Lines.ItemCode = "QM000118";
                    //oPedido.Lines.UnitPrice = 100;

                    //oPedido.Lines.PriceAfterVAT=Convert.ToDouble(DgvDetalle.Rows[i].Cells[3].Value.ToString());
                    //oPedido.Lines.Price = double.Parse(DgvDetalle.Rows[i].Cells[3].Value.ToString());
                    //oPedido.Lines.UnitPrice = double.Parse(DgvDetalle.Rows[i].Cells[3].Value.ToString());



                    oPedido.Lines.Add();
                }
                //oPedido.Lines.LineNum;
                //oPedido.Lines.ItemCode = TxtCodigo.Text;
                //oPedido.Lines.ItemDescription = TxtDescripcion.Text;
                //oPedido.Lines.Quantity = double.Parse(TxtCantidad.Text);
                //oPedido.Lines.UnitPrice = double.Parse(TxtPrecio.Text);
                //oPedido.Lines.UserFields.Fields.Item("U_TipoA").Value = CmbTipoTax.GetItemText(CmbTipoTax.SelectedValue);
                //oPedido.Lines.TaxCode = CmbTipoDeta.GetItemText(CmbTipoDeta.SelectedValue);
                //oPedido.Lines.ItemDetails = "1";

                int resultado = oPedido.Add();
                //Si la transaccion da error:
                if (resultado != 0)
                {
                    MessageBox.Show("Error al agregar Factura: " + oEmpresa.GetLastErrorDescription());
                }
                else
                {
                    MessageBox.Show("Pedido Ingresado Exitosamente");
                    //UPDATE PARA LA FILA
                    SqlCommand cmd = new SqlCommand();
                    //SqlCommand cmd = new SqlCommand(Update, cnn.conexion);
                    cmd.CommandText = "update Pedido_Cabecera set Status='Ingresado a SAP' where ID=@ID";
                    cmd.Connection  = cnn.ObtenerConexion();

                    cmd.Parameters.AddWithValue("@ID", TxtID.Text);

                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Ingresado a SAP!!  " + "@ID" + TxtID.Text);
                    cnn.conexion.Dispose();
                    cnn.conexion.Close();

                    //cnn.DescargarConexion();
                    Limpiar();
                    DgvDetalle.DataSource = null;
                    //limpiar();
                    //FIN DEL UPDATE PARA LA FILA
                }



                //---------------------------------------

                //string Update= "update Persons set nombre=@nombre, apellido=@apellido, fechaingreso=@fecha where id=@id";


                // DgvDetalle.Refresh();
            }
            catch (Exception err)
            {
                //Control de errores
                MessageBox.Show(err.Message, "Advertencia ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Пример #17
0
        public bool CrearDocumento(List <Ticket> pLstTicket, SAPbobsCOM.BoObjectTypes pObjType, string pStrTableBase, int pIntBaseType, string pStrTableDetail)
        {
            bool lBolIsSuccess = false;

            try
            {
                string lStrDocEntry   = string.Empty;
                string lStrCostCenter = GetCostCenter();
                List <TicketDetail>  lLstTicketDetail = new List <TicketDetail>();
                SAPbobsCOM.Documents lObjDocument     = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(pObjType); //SAPbobsCOM.BoObjectTypes.oInvoices);
                foreach (Ticket lObjTicket in pLstTicket)
                {
                    if (pStrTableBase == "ORDR")
                    {
                        lObjDocument.DocObjectCodeEx = "13";
                    }

                    lStrDocEntry          = mObjQueryManager.GetValue("DocEntry", "DocNum", lObjTicket.Number.ToString(), pStrTableBase);
                    lObjDocument.CardCode = lObjTicket.BPCode;

                    if (lObjTicket.CapType == 0)
                    {
                        lObjDocument.DocObjectCode = BoObjectTypes.oInvoices;
                    }
                    lLstTicketDetail = mObjTicketDAO.GetListTicketDetail(lObjTicket.Folio) as List <TicketDetail>;
                    if (pStrTableBase == "OINV")
                    {
                        // lLstTicketDetail = AdjustmentTicket(pLstTicket, true, false);
                    }
                    if (pStrTableBase == "OPCH")
                    {
                        //lLstTicketDetail = AdjustmentTicket(pLstTicket, false, false);
                    }

                    for (int i = 0; i < lLstTicketDetail.Count; i++)
                    {
                        if (lObjTicket.Number != 0 && VerifyDocItem(lStrDocEntry, lLstTicketDetail[i].Item, pStrTableDetail))
                        {
                            lObjDocument.Lines.BaseEntry = int.Parse(lStrDocEntry);
                            lObjDocument.Lines.BaseLine  = lLstTicketDetail[i].BaseLine;
                            lObjDocument.Lines.BaseType  = pIntBaseType;
                        }
                        // lObjDocument.Lines.AccountCode = "2180010000000";
                        if (lLstTicketDetail[i].netWeight < 0)
                        {
                            lLstTicketDetail[i].netWeight *= -1;
                        }

                        lObjDocument.Lines.ItemCode = lLstTicketDetail[i].Item;

                        lObjDocument.Lines.UnitsOfMeasurment = 0;
                        lObjDocument.Lines.UnitPrice         = lLstTicketDetail[i].Price;
                        lObjDocument.Lines.COGSCostingCode   = lStrCostCenter;

                        if (lObjTicket.CapType == 4)
                        {
                            lObjDocument.Lines.Quantity          = 1;
                            lObjDocument.Lines.UnitsOfMeasurment = 1;
                            string ss = lObjDocument.Lines.UoMCode;
                        }
                        else
                        {
                            lObjDocument.Lines.Quantity = lLstTicketDetail[i].netWeight;
                        }
                        lObjDocument.Lines.WarehouseCode = lLstTicketDetail[i].WhsCode;
                        // lObjDocument.Lines.ProjectCode = lObjTicket.Project;
                        lObjDocument.Lines.UserFields.Fields.Item("U_GLO_BagsBales").Value = lLstTicketDetail[i].BagsBales;
                        lObjDocument.Lines.UserFields.Fields.Item("U_PL_Ticket").Value     = lLstTicketDetail[i].Folio;
                        lObjDocument.Lines.Add();
                    }
                }
                if (lObjDocument.Add() != 0)
                {
                    UIApplication.ShowMessageBox(string.Format("Exception: {0}", DIApplication.Company.GetLastErrorDescription()));
                    LogService.WriteError("[ERROR]" + DIApplication.Company.GetLastErrorDescription());
                }
                else
                {
                    lBolIsSuccess = true;
                    LogService.WriteSuccess("[CrearDocumento] DocNum:" + lObjDocument.DocNum);
                    MemoryUtility.ReleaseComObject(lObjDocument);
                    UIApplication.ShowMessageBox(string.Format("Documento realizado correctamente"));
                }
            }
            catch (Exception ex)
            {
                UIApplication.ShowMessageBox(string.Format("Exception: {0}", ex.Message));
                LogService.WriteError("[CrearDocumento]" + ex.Message);
                LogService.WriteError(ex);
            }
            return(lBolIsSuccess);
        }
Пример #18
0
        private void InvoiceRDraft()
        {
            SAPbouiCOM.Form lObjFormDraft = null;

            int  lIntRetCode = 0;
            int  lIntKeyD    = 0;
            int  lIntCounter = 0;
            int  lIntPrevKey = 0;
            bool lBoolDraft  = false;

            string lStrArticle = mObjRejectedDAO.GetArticleToInvoice();

            lObjDraftInvoice = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);



            var lVarRejectedToInv = from p in lListRejectedToInvoice group p by p.Client into gr select gr;

            try
            {
                foreach (var lVarClient in lVarRejectedToInv)
                {
                    foreach (var item in lVarClient)
                    {
                        lObjErrorListDTO = new DTO.ErrorListDTO();
                        lStrReference    = lStrMainRWhs + "_" + item.Inspection;

                        if (!CheckThreeDays(lIntCounter))
                        {
                            if (!HasInvoice(lStrReference, item.DistNumb))
                            {
                                if (SetCosts(item.Inspection, lIntCounter) != -1)
                                {
                                    lIntKeyD = mObjRejectedDAO.GetDraftKey(lStrReference, lStrArticle);

                                    if (lIntKeyD > 0 && lIntKeyD != lIntPrevKey)
                                    {
                                        lObjDraftInvoice.GetByKey(lIntKeyD);

                                        lObjDraftInvoice.Remove();
                                        lIntKeyD = 0;
                                    }
                                    if (lIntKeyD == 0)
                                    {
                                        lObjDraftInvoice.DocObjectCodeEx = "13";
                                        lObjDraftInvoice.CardCode        = item.Client;
                                        lObjDraftInvoice.Lines.FreeText  = lStrReference;
                                        lObjDraftInvoice.Lines.ItemCode  = lStrArticle;
                                        lObjDraftInvoice.Lines.TaxCode   = mObjRejectedDAO.GetTaxCode(lStrArticle);
                                        lObjDraftInvoice.Lines.Quantity  = item.QuantityConcept;
                                        lObjDraftInvoice.Lines.LineTotal = item.Price;

                                        lObjDraftInvoice.Lines.Add();

                                        lBoolDraft = true;

                                        lObjErrorListDTO.Option     = "Correct";
                                        lObjErrorListDTO.Inspection = lListRejectedToInvoice[lIntCounter].Inspection;
                                        lObjlstErrorDTO.Add(lObjErrorListDTO);
                                    }
                                    //else
                                    //{
                                    //    lObjErrorListDTO.Option = "HasDraft";
                                    //    lObjErrorListDTO.Inspection = lListRejectedToInvoice[lIntCounter].Inspection;
                                    //    lObjlstErrorDTO.Add(lObjErrorListDTO);

                                    //    if (lObjChckBox.Checked)
                                    //    {

                                    //        lIntKeyD = mObjRejectedDAO.GetDraftKey(lStrReference, lStrArticle);

                                    //        if (lIntKeyD > 0 && lIntKeyD != lIntPrevKey)
                                    //        {
                                    //            lObjDraftInvoice.GetByKey(lIntKeyD);
                                    //            if (lObjDraftInvoice.DocDate < lObjDatetime)
                                    //            {
                                    //                lObjDraftInvoice.Remove();
                                    //            }
                                    //            else
                                    //            {

                                    //                lObjFormDraft = Application.SBO_Application.OpenForm((SAPbouiCOM.BoFormObjectEnum)112, "", lIntKeyD.ToString());
                                    //                lIntPrevKey = lIntKeyD;
                                    //            }
                                    //        }
                                    //    }
                                    //}
                                }
                                else
                                {
                                    lObjErrorListDTO.Option     = "InvalidDate";
                                    lObjErrorListDTO.Inspection = lListRejectedToInvoice[lIntCounter].Inspection.ToString();

                                    lObjlstErrorDTO.Add(lObjErrorListDTO);
                                }
                            }
                            else
                            {
                                lObjErrorListDTO.Option     = "WithInvoice";
                                lObjErrorListDTO.Inspection = lListRejectedToInvoice[lIntCounter].Inspection.ToString();

                                lObjlstErrorDTO.Add(lObjErrorListDTO);
                            }
                        }
                        else
                        {
                            lObjErrorListDTO.Option     = "OnTime";
                            lObjErrorListDTO.Inspection = lListRejectedToInvoice[lIntCounter].Inspection.ToString();

                            lObjlstErrorDTO.Add(lObjErrorListDTO);
                        }

                        lIntCounter++;
                    }

                    if (lBoolDraft)
                    {
                        lIntRetCode = lObjDraftInvoice.Add();

                        if (lIntRetCode != 0)
                        {
                            string lStrError = DIApplication.Company.GetLastErrorDescription();
                            Application.SBO_Application.StatusBar.SetText(lStrError
                                                                          , SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                        }

                        lIntKeyD = mObjRejectedDAO.GetDraftKey(lStrReference, lStrArticle);

                        if (lObjChckBox.Checked)
                        {
                            if (lIntKeyD > 0 && lIntKeyD != lIntPrevKey)
                            {
                                lObjFormDraft = Application.SBO_Application.OpenForm((SAPbouiCOM.BoFormObjectEnum) 112, "", lIntKeyD.ToString());
                                lIntPrevKey   = lIntKeyD;
                            }
                        }
                    }
                }
            }
            catch (Exception lObjException)
            {
                throw new DAOException(lObjException.Message, lObjException);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjDraftInvoice);
            }
        }
Пример #19
0
        private static void OpenGoodsIssuesForm(DocumentDTO pObjExitDTO, string pStrType, UserValues pObjUser)
        {
            int    lIntDraftKey    = 0;
            string lStrObjectCode  = "60";
            var    result          = new ResultDTO();
            var    distributionDAO = new DistributionDAO();

            //lIntDraftKey = distributionDAO.GetDraftKey(pObjExitDTO.Document.Code);
            //if (lIntDraftKey == 0)
            //{
            SAPbobsCOM.Documents lObjDraftInvoice = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);

            lObjDraftInvoice.DocObjectCodeEx = "60";
            lObjDraftInvoice.Series          = distributionDAO.GetSeries(pObjUser.WhsCode, lStrObjectCode);
            lObjDraftInvoice.UserFields.Fields.Item("U_GLO_BusinessPartner").Value = pObjExitDTO.Document.Code;
            lObjDraftInvoice.UserFields.Fields.Item("U_PE_Origin").Value           = pStrType;
            lObjDraftInvoice.UserFields.Fields.Item("U_GLO_Status").Value          = !pObjUser.AppraisalValidation ? "O" : "A";
            lObjDraftInvoice.UserFields.Fields.Item("U_GLO_InMo").Value            = "S-GAN";


            foreach (var line in pObjExitDTO.Lines)
            {
                lObjDraftInvoice.Lines.ItemCode      = line.ItemCode;
                lObjDraftInvoice.Lines.Quantity      = line.Quantity;
                lObjDraftInvoice.Lines.WarehouseCode = line.Corral;
                lObjDraftInvoice.Lines.CostingCode   = pObjUser.Area;

                var batches = pObjExitDTO.Batches.Where(b => b.Corral == line.Corral && b.AuctDate == line.AuctDate && b.ItemCode == line.ItemCode).AsParallel().ToList();
                foreach (var batch in batches)
                {
                    if (batches.Count == 1)
                    {
                        lObjDraftInvoice.Lines.BatchNumbers.Quantity    = line.Quantity;
                        lObjDraftInvoice.Lines.BatchNumbers.BatchNumber = batch.Batch;
                    }
                    else
                    {
                        if (line.Quantity - batch.Quantity > 0)
                        {
                            lObjDraftInvoice.Lines.BatchNumbers.BatchNumber = batch.Batch;
                            lObjDraftInvoice.Lines.BatchNumbers.Quantity    = batch.Quantity;
                            line.Quantity -= batch.Quantity;
                        }
                        else if (line.Quantity > 0)
                        {
                            lObjDraftInvoice.Lines.BatchNumbers.BatchNumber = batch.Batch;
                            lObjDraftInvoice.Lines.BatchNumbers.Quantity    = line.Quantity;
                            line.Quantity -= batch.Quantity;
                        }
                    }
                    lObjDraftInvoice.Lines.BatchNumbers.Add();
                }
                lObjDraftInvoice.Lines.Add();
            }

            if (lObjDraftInvoice.Add() != 0)
            {
                string gg = DIApplication.Company.GetLastErrorDescription();
                LogService.WriteError("InventoryExitDI (CreateDocument) " + DIApplication.Company.GetLastErrorDescription());
            }
            else
            {
                //lIntDraftKey = distributionDAO.GetDraftKey(pObjExitDTO.Document.Code);
                lIntDraftKey = int.Parse(DIApplication.Company.GetNewObjectKey());

                if (lIntDraftKey > 0)
                {
                    OpenDraft(lIntDraftKey);
                }
            }
            //}
            //else
            //{
            //    OpenDraft(lIntDraftKey);
            //}
        }
Пример #20
0
        public string postDocument()
        {
            Program.objHrmsUI.loadSettings();
            string outStr  = "";
            string TaxCode = Program.objHrmsUI.getSetting("TAX").ToString();

            try
            {
                if (dtORDR.Rows.Count == 0)
                {
                    return("No Items");
                }

                SAPbobsCOM.Documents        Doc = (SAPbobsCOM.Documents)Program.objHrmsUI.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseOrders);
                SAPbobsCOM.BusinessPartners bp  = (SAPbobsCOM.BusinessPartners)Program.objHrmsUI.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners);

                bool bpexist = bp.GetByKey(dtHead.GetValue("CardCode", 0).ToString());


                Doc.CardCode   = dtHead.GetValue("CardCode", 0).ToString();
                Doc.DocDate    = Convert.ToDateTime(dtHead.GetValue("InvDate", 0));
                Doc.DocDueDate = Convert.ToDateTime(dtHead.GetValue("InvDate", 0));
                // Doc.SalesPersonCode = Convert.ToInt16( Program.objHrmsUI.settings["WebSlpCode"].ToString());
                Doc.PickRemark      = "LTD A/R Invoice " + dtHead.GetValue("InvNum", 0).ToString(); // dtORDR.GetValue("NumAtCard", 0).ToString();
                Doc.NumAtCard       = "LTD Inv # " + dtHead.GetValue("InvNum", 0).ToString();
                Doc.Comments        = dtHead.GetValue("REM", 0).ToString();
                Doc.DiscountPercent = Convert.ToDouble(dtHead.GetValue("DP", 0));
                int ItemLineNum = -1;
                for (int i = 0; i < dtRDR1.Rows.Count; i++)
                {
                    if (dtRDR1.GetValue("ItemCode", i).ToString() != "")
                    {
                        Doc.Lines.ItemCode        = dtRDR1.GetValue("ItemCode", i).ToString();
                        Doc.Lines.ItemDescription = dtRDR1.GetValue("ItemName", i).ToString(); //rs.Fields.Item("ItemName").Value;
                        Doc.Lines.Quantity        = Convert.ToDouble(dtRDR1.GetValue("Qty", i));
                        Doc.Lines.UnitPrice       = Convert.ToDouble(dtRDR1.GetValue("Price", i));
                        Doc.Lines.DiscountPercent = Convert.ToDouble(dtRDR1.GetValue("DiscP", i));
                        Doc.Lines.UoMEntry        = getUomEntry(dtRDR1.GetValue("UOM", i).ToString());
                        // Doc.Lines.VatGroup = TaxCode.ToString();
                        Doc.Lines.TaxCode = TaxCode;
                        Doc.Lines.Add();
                        ItemLineNum++;
                    }
                    else
                    {
                        Doc.SpecialLines.LineType        = SAPbobsCOM.BoDocSpecialLineType.dslt_Text;
                        Doc.SpecialLines.LineText        = dtRDR1.GetValue("ItemName", i).ToString();
                        Doc.SpecialLines.AfterLineNumber = ItemLineNum;
                        Doc.SpecialLines.Add();
                    }
                }

                try
                {
                    if (Doc.Add() != 0)
                    {
                        int    erroCode = 0;
                        string errDescr = "";
                        Program.objHrmsUI.oCompany.GetLastError(out erroCode, out errDescr);
                        outStr = "Error:" + errDescr + outStr;
                        oApplication.StatusBar.SetText("Failed to post Order : " + errDescr);
                    }
                    else
                    {
                        outStr = Convert.ToString(Program.objHrmsUI.oCompany.GetNewObjectKey());
                    }
                }
                catch (Exception ex)
                {
                    oApplication.StatusBar.SetText("Failed in Exec Query on Posting Document.  : " + ex.Message);
                }
                finally
                {
                }
            }

            catch (Exception ex)
            {
                oApplication.SetStatusBarMessage("Error in posting document : " + ex.Message);
            }
            return(outStr);
        }
Пример #21
0
        public string funEnviarSalMercanciaSAP()
        {
            try {
                string mError = "";
                int    iError = 0;
                int    i      = 0;
                //Realizamos la conexion a SAP
                csAccesoDatos.proIniciarSesionSAP();
                //Verificamos si el documento ya se encuentra en SAP
                DataTable dtInventarioSAP = funVerificarSalInventarioSAP(DocNombre, CabNumero);
                if (dtInventarioSAP.Rows.Count > 0)
                {
                    //Recuperamos en las variables los valores de SAP
                    CabDocEntrySAP = int.Parse(dtInventarioSAP.Rows[0]["DocEntry"].ToString());
                    CabNumeroSAP   = int.Parse(dtInventarioSAP.Rows[0]["DocNum"].ToString());
                    //Actualizamos en el movimiento los datos de SAP
                    proActMovInventarioSalida(CabDocEntrySAP, CabNumeroSAP, CabCodigo);
                    return(mError);
                }
                else
                {
                    //Instanciamos la variable con el objeto de SAP Salida de mercancias
                    SAPbobsCOM.Documents varOIGE = csConexionSap.objConexionSap.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenExit);

                    varOIGE.Series           = clsSegDocumento.funRecNumSerieSAPSalida(DocCodigo);                          //Serie
                    varOIGE.DocDate          = (DateTime)CabFecha;                                                          //Fecha de contabilización
                    varOIGE.TaxDate          = (DateTime)CabFecha;                                                          //Fecha de documento
                    varOIGE.Comments         = CabComentario;                                                               //Comentarios
                    varOIGE.JournalMemo      = DocNombre + "-" + CabNumero + " " + CabComenDiario;                          //Comentario asiento contable
                    varOIGE.PaymentGroupCode = -2;                                                                          //Lista de precios (Ultimo precio determinado)
                    //Valores del codigo y nombre del movimiento
                    varOIGE.UserFields.Fields.Item("U_Ita_codmovimiento").Value = IdMotivo.ToString();                      //Codigo movimiento
                    varOIGE.UserFields.Fields.Item("U_Ita_movimiento").Value    = Motivo;                                   //Movimientos
                    //Valores de la auditoria del sistema umbrella
                    varOIGE.UserFields.Fields.Item("U_Ita_sysusuario").Value   = clsVariablesGlobales.varCodUsuario;        //Usuario del sistema umbrella
                    varOIGE.UserFields.Fields.Item("U_Ita_sysfecha").Value     = DateTime.Now.ToString("dd/MM/yyyy HH:mm"); //Fecha del sistema umbrella
                    varOIGE.UserFields.Fields.Item("U_Ita_sysip").Value        = clsVariablesGlobales.varIpMaquina;         //Ip del sistema umbrella
                    varOIGE.UserFields.Fields.Item("U_Ita_sysdocumento").Value = DocNombre;                                 //Documento del sistema umbrella
                    varOIGE.UserFields.Fields.Item("U_Ita_sysnumero").Value    = CabNumero.ToString();                      //Numero del sistema umbrella
                    //Recuperamos informacion de los detalles del movimiento
                    List <clsInvMovimientoDet> objDetalle = new List <clsInvMovimientoDet>();
                    clsInvMovimientoDet.proListar(CabCodigo, out objDetalle);
                    //Recorremos los detalles del movimiento
                    foreach (clsInvMovimientoDet objFilaDetalle in objDetalle)
                    {
                        //En caso de que la variable i se ha mayor a cero se debe agregar una nueva linea
                        if (!i.Equals(0))
                        {
                            varOIGE.Lines.Add();
                        }
                        varOIGE.Lines.SetCurrentLine(i);
                        varOIGE.Lines.WarehouseCode   = BodCodigo;                //Almacen
                        varOIGE.Lines.ItemCode        = objFilaDetalle.IteCodigo; //Código
                        varOIGE.Lines.ItemDescription = objFilaDetalle.IteNombre; //Descripción
                        //Informacion de la chapeta en caso de que sea requerido la chapeta/lote
                        if (objFilaDetalle.DetIdDestino != null)
                        {
                            if (objFilaDetalle.DetTipDestino.Equals("A"))
                            {
                                varOIGE.Lines.UserFields.Fields.Item("U_Ita_arete").Value = objFilaDetalle.DetIdDestino;                                          //Arete
                            }
                            else if (objFilaDetalle.DetTipDestino.Equals("L"))
                            {
                                varOIGE.Lines.UserFields.Fields.Item("U_Ita_lote").Value = objFilaDetalle.DetIdDestino;                                               //Lote
                            }
                        }
                        //Informacion de los valores del detalle
                        varOIGE.Lines.Quantity    = double.Parse(objFilaDetalle.DetCantidad.ToString()); //Cantidad
                        varOIGE.Lines.AccountCode = CtaContable;                                         //Compensación de stocks reducir cuenta
                        //Verificamos si tiene centro de costo
                        if (!CcoCodigo.Equals(""))
                        {
                            varOIGE.Lines.CostingCode = CcoCodigo.Substring(0, 2);                      //Centro de responsabilidad
                        }
                        if (!CcoCodigo.Equals(""))
                        {
                            varOIGE.Lines.CostingCode2 = CcoCodigo.Substring(0, 3);                       //Centro de actividad
                        }
                        if (!CcoCodigo.Equals(""))
                        {
                            varOIGE.Lines.CostingCode3 = CcoCodigo;                       //Centro de costo
                        }
                        //Verificamos si tiene proyecto
                        if (!PryCodigo.Equals(""))
                        {
                            varOIGE.Lines.ProjectCode = PryCodigo; //Proyecto
                        }
                        int j = 0;                                 //Variable utilizada para los lotes
                        //Verificamos si el item requiere lote
                        if (objFilaDetalle.IteTieLote.ToUpper().Equals("Y"))
                        {
                            //Recuperamos la informacion de los lotes segun el item y la bodega
                            DataTable dtLote      = clsInvItem.funRecLote(objFilaDetalle.IteCodigo, BodCodigo);
                            double    varSaldo    = dtLote.Rows.Count.Equals(0) ? 0 : double.Parse(dtLote.Compute("Sum(StkDisponible)", "").ToString());
                            double    varCantidad = double.Parse(objFilaDetalle.DetCantidad.ToString());
                            //Verificamos si el saldo del item no cae en negativo con respecto a lo que se necesita
                            if (varCantidad > varSaldo)
                            {
                                throw new Exception(string.Format("El Item {0} - {1} tiene un saldo de {2} y lo requerido es {3}", objFilaDetalle.IteCodigo, objFilaDetalle.IteNombre, varSaldo, varCantidad));
                            }
                            //Recorremos los lotes disponibles hasta cumplir con la candidad deseada
                            foreach (DataRow drLote in dtLote.Rows)
                            {
                                string varLotCodigo     = drLote["LotCodigo"].ToString();                   //Recuperamos el codigo del lote
                                double varStkDisponible = double.Parse(drLote["StkDisponible"].ToString()); //Recuperamos la cantidad disponible de ese lote
                                //Agragamos una nueva linea de Lote
                                if (j > 0)
                                {
                                    varOIGE.Lines.BatchNumbers.Add();
                                }
                                varOIGE.Lines.BatchNumbers.SetCurrentLine(j);          //Nos posicionamos en la linea del lote recien creada
                                varOIGE.Lines.BatchNumbers.BatchNumber = varLotCodigo; //Codigo del lote que vamos a utilizar
                                //Validamos si la cantidad que dispone el lote seleccionado es suficiente para la cantidad requerida
                                if (varCantidad <= varStkDisponible)
                                {
                                    varOIGE.Lines.BatchNumbers.Quantity = varCantidad;
                                    break;
                                }
                                else
                                {
                                    varOIGE.Lines.BatchNumbers.Quantity = varStkDisponible;
                                    varCantidad -= varStkDisponible;
                                    j++; //Secuencial utilizado para las lineas del lote
                                }
                            }
                        }
                        i++; //Secuencial utilizado para las lineas del detalle
                    }
                    iError = varOIGE.Add();
                    if (!iError.Equals(0))
                    {
                        csConexionSap.objConexionSap.GetLastError(out iError, out mError);
                        return(mError);
                    }
                    else
                    {
                        int varDocEntrySAPSalida = 0;
                        int.TryParse(csConexionSap.objConexionSap.GetNewObjectKey().ToString(), out varDocEntrySAPSalida);
                        varOIGE.GetByKey(varDocEntrySAPSalida);
                        int varDocNumSAPSalida = varOIGE.DocNum;
                        //Actualizamos los costos de los movimientoes de inventario
                        proActCstAcumulado(varDocEntrySAPSalida, CabCodigo);
                        //Actualizamos en el movimiento los datos de SAP
                        proActMovInventarioSalida(varDocEntrySAPSalida, varDocNumSAPSalida, CabCodigo);
                        return(mError);
                    }
                }
            }
            catch (Exception e) { throw new Exception(e.Message); }
            finally { csAccesoDatos.proFinalizarSesionSAP(); }
        }
Пример #22
0
        /// <summary>
        /// Crear factura.
        /// </summary>
        public bool CreateDocument(PurchaseXMLDTO pObjPurchase, bool lBolCreatePayment)
        {
            bool   lBolIsSuccess = false;
            string lStrAttachXML = string.Empty;
            string lStrAttachPDF = string.Empty;

            //SAPbobsCOM.Documents lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices);
            SAPbobsCOM.Documents lObjDocument = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
            try
            {
                //Draft Type Document
                lObjDocument.DocObjectCode = BoObjectTypes.oPurchaseInvoices;

                /*double ldbl = Convert.ToDouble(pObjPurchase.Total);
                 * lObjDocument.DocTotal = ldbl;*/
                string lStrCostCenter = mObjPurchaseServiceFactory.GetPurchaseInvoiceService().GetCostCenter();

                lObjDocument.CardCode   = pObjPurchase.CardCode;
                lObjDocument.EDocNum    = pObjPurchase.FolioFiscal;
                lObjDocument.TaxDate    = pObjPurchase.TaxDate;
                lObjDocument.DocDate    = pObjPurchase.DocDate;
                lObjDocument.Comments   = pObjPurchase.Obs;
                lObjDocument.NumAtCard  = pObjPurchase.ReferenceFolio;
                lObjDocument.DocDueDate = pObjPurchase.TaxDate.AddMonths(1);
                lObjDocument.UserFields.Fields.Item("U_UDF_UUID").Value = pObjPurchase.FolioFiscal;
                //lObjDocument.UserFields.Fields.Item("U_GLO_DocEUG").Value = String.IsNullOrEmpty(pObjPurchase.CodeMov) ? "" : pObjPurchase.CodeMov;
                lObjDocument.UserFields.Fields.Item("U_GLO_ObjTUG").Value  = "frmReceipts";
                lObjDocument.UserFields.Fields.Item("U_FolioFiscal").Value = pObjPurchase.FolioFiscal;
                lObjDocument.UserFields.Fields.Item("U_GLO_Memo").Value    = pObjPurchase.Obs;
                string lStrFile = AttatchFile(pObjPurchase.XMLFile);
                if (!string.IsNullOrEmpty(lStrFile))
                {
                    lObjDocument.UserFields.Fields.Item("U_ArchivoXML").Value = AttatchFile(pObjPurchase.XMLFile);
                    lObjDocument.UserFields.Fields.Item("U_ArchivoPDF").Value = AttatchFile(pObjPurchase.PDFFile);
                }
                else
                {
                    return(false);
                }

                lObjDocument.UserFields.Fields.Item("U_MQ_Rise").Value = pObjPurchase.MQRise;
                // lObjDocument.WithholdingTaxData

                //adding reference
                lObjDocument.UserFields.Fields.Item("U_MQ_OrigenFol").Value = pObjPurchase.Folio;                /* (String.IsNullOrEmpty(pObjPurchase.CodeMov)) ?
                                                                                                                  * String.Format("{0}_{1}_{2}", pObjPurchase.Type, pObjPurchase.Area, pObjPurchase.Folio) :
                                                                                                                  * String.Format(pObjPurchase.Type +"_"+ pObjPurchase.CodeMov);*/


                lObjDocument.UserFields.Fields.Item("U_MQ_OrigenFol_Det").Value = pObjPurchase.RowLine;

                bool lbolWithholdingTax = true;

                /*Base = y.First().Base,
                 *      Tax = y.First().Tax,
                 *      TypeFactor = y.First().TypeFactor,
                 *      Rate = y.First().Rate,
                 *      Amount = y.Sum(c => float.Parse(c.Amount)).ToString()*/

                pObjPurchase.WithholdingTax = pObjPurchase.WithholdingTax.GroupBy(x => x.Rate).Select(y => new TaxesXMLDTO
                {
                    Base       = y.First().Base,
                    Tax        = y.First().Tax,
                    TypeFactor = y.First().TypeFactor,
                    Rate       = y.First().Rate,
                    Amount     = y.Sum(c => float.Parse(c.Amount)).ToString()
                }).ToList();



                foreach (TaxesXMLDTO lObjTax in pObjPurchase.WithholdingTax)
                {
                    lObjDocument.WithholdingTaxData.WTCode = mObjPurchaseServiceFactory.GetPurchaseInvoiceService().GetWithholdingTaxCodeBP(Convert.ToDouble(lObjTax.Rate) * 100, lObjDocument.CardCode);
                    if (!string.IsNullOrEmpty(lObjDocument.WithholdingTaxData.WTCode))
                    {
                        lObjDocument.WithholdingTaxData.WTAmount = Convert.ToDouble(lObjTax.Amount);
                        lObjDocument.WithholdingTaxData.Add();
                    }
                    else
                    {
                        lbolWithholdingTax = false;
                    }
                }


                foreach (ConceptsXMLDTO lObjConcept in pObjPurchase.ConceptLines)
                {
                    lObjDocument.Lines.ItemCode        = lObjConcept.CodeItmProd;
                    lObjDocument.Lines.UnitPrice       = Convert.ToDouble(lObjConcept.UnitPrice);
                    lObjDocument.Lines.Quantity        = Convert.ToDouble(lObjConcept.Quantity);
                    lObjDocument.Lines.COGSCostingCode = lObjConcept.CostingCode;
                    if (lObjConcept.AdmOper == "O")
                    {
                        lObjDocument.Lines.AccountCode = mObjPurchaseServiceFactory.GetPurchaseInvoiceService().GetCostAccount(lObjConcept.CodeItmProd);
                    }

                    lObjDocument.Lines.TaxType  = lObjConcept.HasTax ? BoTaxTypes.tt_Yes : BoTaxTypes.tt_No;                     //= BoTaxTypes.tt_No;
                    lObjDocument.Lines.WTLiable = lObjConcept.HasWht ? BoYesNoEnum.tYES : BoYesNoEnum.tNO;
                    lObjDocument.Lines.UserFields.Fields.Item("U_CO_AdmOper").Value = lObjConcept.AdmOper;

                    lObjDocument.Lines.COGSCostingCode2 = lObjConcept.AF;
                    lObjDocument.Lines.ProjectCode      = lObjConcept.Project;
                    lObjDocument.Lines.CostingCode3     = lObjConcept.AGL;

                    //lObjDocument.Lines.
                    lObjDocument.Lines.TaxCode = lObjConcept.TaxCode;
                    //lObjDocument.Lines.TaxTotal = lObjConcept.LstTaxes;
                    if (!string.IsNullOrEmpty(pObjPurchase.MQRise))
                    {
                        string lStrWhsMQ = mObjPurchaseServiceFactory.GetPurchaseInvoiceService().GetMQWhs(lObjConcept.CodeItmProd);
                        if (!string.IsNullOrEmpty(lStrWhsMQ))
                        {
                            lObjConcept.WareHouse = lStrWhsMQ;
                        }
                    }
                    lObjDocument.Lines.WarehouseCode = lObjConcept.WareHouse;                     //mObjPurchaseServiceFactory.GetPurchaseInvoiceService().GetWhouse(lObjConcept.CostingCode);

                    double lDblDesc = 0;
                    if (Convert.ToDecimal(lObjConcept.Discount) > 0)
                    {
                        lDblDesc = Convert.ToDouble(lObjConcept.Discount) / Convert.ToDouble(lObjConcept.Subtotal);
                        //lDblDesc = Math.Round(100 * lDblDesc) / 100;
                        lObjDocument.Lines.DiscountPercent = lDblDesc * 100;
                    }


                    double lDblUnitPrice = Convert.ToDouble(lObjConcept.UnitPrice);
                    lDblUnitPrice = Math.Round(100 * lDblUnitPrice) / 100;

                    double lDblQuantity  = Convert.ToDouble(lObjConcept.Quantity);
                    double lDblAmountXML = Convert.ToDouble(lObjConcept.Subtotal);

                    double lDblAmount = lDblUnitPrice * lDblQuantity;

                    lDblAmount    = Math.Round(100 * lDblAmount) / 100;
                    lDblAmountXML = Math.Round(100 * lDblAmountXML) / 100;


                    if (lDblAmount != lDblAmountXML)
                    {
                        double lDblnewDesc = 0;
                        lDblnewDesc = (lDblAmount / lDblAmountXML) - 1;
                        lObjDocument.Lines.DiscountPercent += lDblnewDesc * 100;
                    }
                    //lObjDocument.Lines.LineTotal = Convert.ToDouble(lObjConcept.Amount);
                    lObjDocument.Lines.Add();


                    // lObjDocument.Lines.
                }



                if (lbolWithholdingTax)
                {
                    if (lObjDocument.Add() != 0)
                    {
                        string lStrError = DIApplication.Company.GetLastErrorDescription();
                        UIApplication.ShowMessageBox(string.Format("Exception: {0}", DIApplication.Company.GetLastErrorDescription()));
                        LogService.WriteError("InvoiceDI (CreateDocument) " + DIApplication.Company.GetLastErrorDescription());
                    }
                    else
                    {
                        lBolIsSuccess = true;

                        string lStrDocEntry = DIApplication.Company.GetNewObjectKey().ToString();


                        pObjPurchase.DocEntry = Convert.ToInt32(lStrDocEntry);
                        PaymentDI lObjPaymentDI = new PaymentDI();

                        //SAPbobsCOM.Documents lObjDocInvoice = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices);
                        SAPbobsCOM.Documents lObjDocInvoice = (SAPbobsCOM.Documents)DIApplication.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
                        lObjDocInvoice.GetByKey(Convert.ToInt32(lStrDocEntry));

                        pObjPurchase.Total = lObjDocInvoice.DocTotal.ToString();

                        if (lBolCreatePayment)
                        {
                            //lBolIsSuccess = lObjPaymentDI.CreatePayment(pObjPurchase);
                            //AddVoucherDetail(pObjPurchase, pObjVoucher);
                        }

                        if (lBolIsSuccess)
                        {
                            LogService.WriteSuccess("Documento realizado correctamente: " + lStrDocEntry);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lBolIsSuccess = false;
                UIApplication.ShowMessageBox(string.Format(ex.Message + "\n" + "Exception: {0}", DIApplication.Company.GetLastErrorDescription()));
                LogService.WriteError("InvoiceDI (CreateDocument) " + DIApplication.Company.GetLastErrorDescription());
                LogService.WriteError("InvoiceDI (CreateDocument) " + ex.Message);
                LogService.WriteError(ex);
            }
            finally
            {
                MemoryUtility.ReleaseComObject(lObjDocument);
            }
            return(lBolIsSuccess);
        }