Example #1
0
        /// <summary>
        /// Load Invoice Line
        /// </summary>
        /// <param name="journal"></param>
        /// <returns>DocLine Array</returns>
        private DocLine[] LoadLines(MJournal journal)
        {
            List <DocLine> list = new List <DocLine>();

            MJournalLine[] lines = journal.GetLines(false);
            for (int i = 0; i < lines.Length; i++)
            {
                MJournalLine line    = lines[i];
                DocLine      docLine = new DocLine(line, this);
                //  --  Source Amounts
                docLine.SetAmount(line.GetAmtSourceDr(), line.GetAmtSourceCr());
                //  --  Converted Amounts
                docLine.SetConvertedAmt(_C_AcctSchema_ID, line.GetAmtAcctDr(), line.GetAmtAcctCr());
                //  --  Account
                MAccount account = line.GetAccount();
                docLine.SetAccount(account);
                //  -- Quantity
                docLine.SetQty(line.GetQty(), false);
                // -- Date
                docLine.SetDateAcct(journal.GetDateAcct());
                //	--	Organization of Line was set to Org of Account
                list.Add(docLine);
            }
            //	Return Array
            int size = list.Count;

            DocLine[] dls = new DocLine[size];
            dls = list.ToArray();
            return(dls);
        }
        /// <summary>
        /// Get or Create Gl Journal Line
        /// </summary>
        /// <param name="Journal">GL Journal</param>
        /// <param name="Line">GL Journal Line</param>
        /// <param name="M_Product_ID">Product</param>
        /// <param name="C_Charge_ID">Charge</param>
        /// <param name="Campaign_ID">Campaign</param>
        /// <param name="Account_ID">Account</param>
        /// <param name="Opprtunity_ID">Opportunity</param>
        /// <param name="Activity_ID">Activity</param>
        /// <param name="BPartner_ID">Business Partner</param>
        /// <param name="Org_Id">Organization</param>
        /// <param name="trxOrg_ID">Transaction Organization</param>
        /// <returns>journal line object</returns>
        public MJournalLine GetOrCreate(MJournal Journal, MJournalLine Line, int M_Product_ID, int C_Charge_ID, int Campaign_ID, int Account_ID, int Opprtunity_ID, int Activity_ID, int BPartner_ID, int Org_Id, int trxOrg_ID)
        {
            MJournalLine retValue = null;
            String       sql      = "SELECT * FROM GL_JournalLine " +
                                    " WHERE  GL_Journal_ID = " + Journal.GetGL_Journal_ID() +
                                    " AND NVL(M_Product_ID,0)=" + M_Product_ID +
                                    " AND NVL(ACCOUNT_ID,0)=" + Account_ID +
                                    " AND NVL(C_CAMPAIGN_ID,0)=" + Campaign_ID +
                                    " AND NVL(C_PROJECT_ID,0)=" + Opprtunity_ID +
                                    " AND NVL(C_ACTIVITY_ID,0)=" + Activity_ID +
                                    " AND NVL(C_BPARTNER_ID,0)=" + BPartner_ID +
                                    " AND NVL(AD_ORGTRX_ID,0)=" + trxOrg_ID +
                                    " AND NVL(AD_ORG_ID,0)=" + Org_Id;


            DataTable   dt  = null;
            IDataReader idr = null;

            try
            {
                idr = DB.ExecuteReader(sql, null, Get_TrxName());
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    retValue = new MJournalLine(Journal.GetCtx(), dr, Get_TrxName());
                }
            }
            catch (Exception ex)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, ex);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
                dt = null;
            }
            if (retValue == null)
            {
                retValue = CreateJournalLine(Journal, Line, M_Product_ID, C_Charge_ID, Campaign_ID, Account_ID, Opprtunity_ID, Activity_ID, BPartner_ID, trxOrg_ID);
            }


            return(retValue);
        }
Example #3
0
        /// <summary>
        /// Load Document Details
        /// </summary>
        /// <returns>error message or null</returns>
        public override String LoadDocumentDetails()
        {
            MJournal journal = (MJournal)GetPO();

            _PostingType     = journal.GetPostingType();
            _C_AcctSchema_ID = journal.GetC_AcctSchema_ID();
            SetDateAcct(journal.GetDateAcct());

            //	Contained Objects
            _lines = LoadLines(journal);
            log.Fine("Lines=" + _lines.Length);
            return(null);
        }
        /// <summary>
        /// Generate Journal Line
        /// </summary>
        /// <param name="Journal">GL Journal</param>
        /// <param name="Line">Gl Journal line</param>
        /// <param name="M_Product_ID">Product</param>
        /// <param name="C_Charge_ID">Charge</param>
        /// <param name="Campaign_ID">Campaign</param>
        /// <param name="Account_ID">Account</param>
        /// <param name="Opprtunity_ID">Opportunity</param>
        /// <param name="Activity_ID">Activity</param>
        /// <param name="BPartner_ID">Business Partner</param>
        /// <param name="trxOrg_ID">Transaction Organization</param>
        /// <returns>object of journal line</returns>
        public MJournalLine CreateJournalLine(MJournal Journal, MJournalLine Line, int M_Product_ID, int C_Charge_ID, int Campaign_ID, int Account_ID, int Opprtunity_ID, int Activity_ID, int BPartner_ID, int trxOrg_ID)
        {
            Line = new MJournalLine(Journal);
            Line.SetLine(lineno);
            Line.Set_ValueNoCheck("Account_ID", Account_ID);
            Line.Set_ValueNoCheck("C_BPartner_ID", BPartner_ID);
            Line.Set_ValueNoCheck("M_Product_ID", M_Product_ID);
            Line.SetAD_OrgTrx_ID(trxOrg_ID);
            //Line.Set_ValueNoCheck("C_Charge_ID", C_Charge_ID);
            Line.Set_ValueNoCheck("C_Campaign_ID", Campaign_ID);
            Line.Set_ValueNoCheck("C_Project_ID", Opprtunity_ID);
            Line.Set_ValueNoCheck("C_Activity_ID", Activity_ID);


            return(Line);
        }
Example #5
0
        }       //	createGLJournal

        /// <summary>
        ///  Create Balancing Entry
        /// </summary>
        /// <param name="asDefaultAccts">acct schema default accounts</param>
        /// <param name="journal">journal</param>
        /// <param name="drTotal">dr</param>
        /// <param name="crTotal">cr</param>
        /// <param name="AD_Org_ID">org</param>
        /// <param name="lineNo">lineno base line no</param>
        private void CreateBalancing(MAcctSchemaDefault asDefaultAccts, MJournal journal,
                                     Decimal drTotal, Decimal crTotal, int AD_Org_ID, int lineNo)
        {
            if (journal == null)
            {
                throw new ArgumentException("Jornal is null");
            }
            //		CR Entry = Gain
            if (Env.Signum(drTotal) != 0)
            {
                MJournalLine line = new MJournalLine(journal);
                line.SetLine(lineNo + 1);
                MAccount bas  = MAccount.Get(GetCtx(), asDefaultAccts.GetUnrealizedGain_Acct());
                MAccount acct = MAccount.Get(GetCtx(), asDefaultAccts.GetAD_Client_ID(), AD_Org_ID,
                                             asDefaultAccts.GetC_AcctSchema_ID(), bas.GetAccount_ID(), bas.GetC_SubAcct_ID(),
                                             bas.GetM_Product_ID(), bas.GetC_BPartner_ID(), bas.GetAD_OrgTrx_ID(),
                                             bas.GetC_LocFrom_ID(), bas.GetC_LocTo_ID(), bas.GetC_SalesRegion_ID(),
                                             bas.GetC_Project_ID(), bas.GetC_Campaign_ID(), bas.GetC_Activity_ID(),
                                             bas.GetUser1_ID(), bas.GetUser2_ID(), bas.GetUserElement1_ID(), bas.GetUserElement2_ID());
                line.SetDescription(Msg.GetElement(GetCtx(), "UnrealizedGain_Acct"));
                line.SetC_ValidCombination_ID(acct.GetC_ValidCombination_ID());
                line.SetAmtSourceCr(drTotal);
                line.SetAmtAcctCr(drTotal);
                line.Save();
            }
            //	DR Entry = Loss
            if (Env.Signum(crTotal) != 0)
            {
                MJournalLine line = new MJournalLine(journal);
                line.SetLine(lineNo + 2);
                MAccount bas  = MAccount.Get(GetCtx(), asDefaultAccts.GetUnrealizedLoss_Acct());
                MAccount acct = MAccount.Get(GetCtx(), asDefaultAccts.GetAD_Client_ID(), AD_Org_ID,
                                             asDefaultAccts.GetC_AcctSchema_ID(), bas.GetAccount_ID(), bas.GetC_SubAcct_ID(),
                                             bas.GetM_Product_ID(), bas.GetC_BPartner_ID(), bas.GetAD_OrgTrx_ID(),
                                             bas.GetC_LocFrom_ID(), bas.GetC_LocTo_ID(), bas.GetC_SalesRegion_ID(),
                                             bas.GetC_Project_ID(), bas.GetC_Campaign_ID(), bas.GetC_Activity_ID(),
                                             bas.GetUser1_ID(), bas.GetUser2_ID(), bas.GetUserElement1_ID(), bas.GetUserElement2_ID());
                line.SetDescription(Msg.GetElement(GetCtx(), "UnrealizedLoss_Acct"));
                line.SetC_ValidCombination_ID(acct.GetC_ValidCombination_ID());
                line.SetAmtSourceDr(crTotal);
                line.SetAmtAcctDr(crTotal);
                line.Save();
            }
        } //	createBalancing
Example #6
0
        public bool Collision(ICollision obj)
        {
            string name1, name2;

            if (obj.Rect.IntersectsWith(Rect))
            {
                if (this is Bullets)
                {
                    name1 = "Пуля";
                }
                else if (this is Ship)
                {
                    name1 = "Корабль";
                }
                else
                {
                    name1 = "Неизвестный объект";
                }

                if (obj is Asteroid)
                {
                    name2 = "Астероидом";
                }
                else if (obj is Life)
                {
                    name2 = "Аптечкой";
                }
                else
                {
                    name2 = "Неизвестный объект";
                }

                MJournal.Invoke($"{name1} столкнулся с {name2}");
            }
            ;
            return(obj.Rect.IntersectsWith(Rect));
        }
Example #7
0
        /// <summary>
        /// Load Invoice Line
        /// </summary>
        /// <param name="journal"></param>
        /// <returns>DocLine Array</returns>
        private DocLine[] LoadLines(MJournal journal)
        {
            MAcctSchema    mSc  = new MAcctSchema(GetCtx(), _C_AcctSchema_ID, null);
            List <DocLine> list = new List <DocLine>();

            MJournalLine[] lines = journal.GetLines(false);
            record_Id = lines[0].GetGL_Journal_ID();

            for (int i = 0; i < lines.Length; i++)
            {
                MJournalLine line = lines[i];

                if (line.GetElementType() == null)
                {
                    DocLine docLine = new DocLine(line, this);
                    //  --  Source Amounts
                    docLine.SetAmount(line.GetAmtAcctDr(), line.GetAmtAcctCr());
                    //  --  Converted Amounts
                    // no need to update converted amount here
                    //docLine.SetConvertedAmt(_C_AcctSchema_ID, line.GetAmtAcctDr(), line.GetAmtAcctCr());
                    //  --  Account
                    MAccount account = line.GetAccount();
                    docLine.SetAccount(account);
                    //  -- Quantity
                    docLine.SetQty(line.GetQty(), false);
                    // -- Date
                    docLine.SetDateAcct(journal.GetDateAcct());
                    //	--	Organization of Line was set to Org of Account
                    list.Add(docLine);
                }
                else
                {
                    string  sql = "SELECT * FROM GL_LineDimension WHERE GL_JournalLine_ID=" + line.Get_ID();
                    DataSet ds  = DB.ExecuteDataset(sql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int m = 0; m < ds.Tables[0].Rows.Count; m++)
                        {
                            DataRow            dr   = ds.Tables[0].Rows[m];
                            X_GL_LineDimension lDim = new X_GL_LineDimension(GetCtx(), dr, null);

                            DocLine docLine = new DocLine(lDim, this);
                            //  --  Source Amounts


                            decimal cRate = line.GetCurrencyRate();
                            if (cRate == 0)
                            {
                                cRate = 1;
                            }
                            decimal amtAcctCr = 0;
                            decimal amtAcctDr = 0;

                            //MAcctSchema mSc = new MAcctSchema(GetCtx(), _C_AcctSchema_ID, null);


                            if (line.GetAmtSourceDr() != 0)
                            {
                                amtAcctDr = lDim.GetAmount() * cRate;
                                docLine.SetAmount(amtAcctDr, 0);
                                amtAcctDr = Decimal.Round(amtAcctDr, mSc.GetStdPrecision());
                            }
                            else
                            {
                                amtAcctCr = lDim.GetAmount() * cRate;
                                docLine.SetAmount(0, amtAcctCr);
                                amtAcctCr = Decimal.Round(amtAcctCr, mSc.GetStdPrecision());
                            }
                            //  --  Converted Amounts
                            // no need to update converted amount here
                            //docLine.SetConvertedAmt(_C_AcctSchema_ID, amtAcctDr, amtAcctCr);
                            //  --  Account
                            MAccount account = line.GetAccount();


                            docLine.SetAccount(account);
                            //  -- Quantity
                            docLine.SetQty(lDim.GetQty(), false);
                            // -- Date
                            docLine.SetDateAcct(journal.GetDateAcct());

                            // -- User Dimension
                            docLine = SetUserDimension(lDim, docLine);

                            //	--	Organization of Line was set to Org of Account
                            list.Add(docLine);
                        }
                    }
                }
            }
            //	Return Array
            int size = list.Count;

            DocLine[] dls = new DocLine[size];
            dls = list.ToArray();
            return(dls);
        }
Example #8
0
 public void Die()
 {
     MessageDie?.Invoke();
     MJournal?.Invoke("Корабль умер");
 }
        protected override string DoIt()
        {
            ds = new DataSet();

            ds = DB.ExecuteDataset("SELECT C_Recurring_ID From C_Recurring Where IsActive='Y' AND AD_Client_ID=" + GetAD_Client_ID()
                                   + " AND TRUNC(DateNextRun)=" + GlobalVariable.TO_DATE(DateTime.Now, true));
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                for (Int32 i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Recurring = new MRecurring(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Recurring_ID"]), Get_Trx());
                    dateDoc   = Recurring.GetDateNextRun();
                    if (dateDoc != null && Recurring.CalculateRuns())
                    {
                        //  throw new Exception("No Runs Left");
                        MRecurringRun run = new MRecurringRun(GetCtx(), Recurring);
                        String        msg = "@Created@ ";
                        // if (Recurring.GetDateNextRun() == DateTime.Now.Date || Recurring.GetDateNextRun() == null)
                        //{
                        //	Copy
                        if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Order))
                        {
                            MOrder from  = new MOrder(GetCtx(), Recurring.GetC_Order_ID(), Get_TrxName());
                            MOrder order = MOrder.CopyFrom(from, dateDoc,
                                                           from.GetC_DocType_ID(), false, false, Get_TrxName());
                            run.SetC_Order_ID(order.GetC_Order_ID());
                            msg += order.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Invoice))
                        {
                            MInvoice from    = new MInvoice(GetCtx(), Recurring.GetC_Invoice_ID(), Get_TrxName());
                            MInvoice invoice = MInvoice.CopyFrom(from, dateDoc,
                                                                 from.GetC_DocType_ID(), false, Get_TrxName(), false);
                            run.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                            msg += invoice.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Project))
                        {
                            MProject project = MProject.CopyFrom(GetCtx(), Recurring.GetC_Project_ID(), dateDoc, Get_TrxName());
                            run.SetC_Project_ID(project.GetC_Project_ID());
                            msg += project.GetValue();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournalBatch))
                        {
                            MJournalBatch journal = MJournalBatch.CopyFrom(GetCtx(), Recurring.GetGL_JournalBatch_ID(), dateDoc, Get_TrxName());
                            run.SetGL_JournalBatch_ID(journal.GetGL_JournalBatch_ID());
                            msg += journal.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournal))
                        {
                            MJournal Journal = MJournal.CopyFrom(GetCtx(), Recurring.GetGL_Journal_ID(), dateDoc, Get_TrxName());
                            run.SetGL_Journal_ID(Journal.GetGL_Journal_ID());
                            msg += Journal.GetDocumentNo();
                        }
                        else if (Recurring.GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Payment))
                        {
                            MPayment from    = new MPayment(GetCtx(), Recurring.GetC_Payment_ID(), Get_TrxName());
                            MPayment payment = MPayment.CopyFrom(from, dateDoc,
                                                                 from.GetC_DocType_ID(), Get_TrxName());
                            run.SetC_Payment_ID(payment.GetC_Payment_ID());
                            msg += payment.GetDocumentNo();
                        }
                        //else
                        //  return "Invalid @RecurringType@ = " + Recurring.GetRecurringType();
                        if (run.Save(Get_TrxName()))
                        {
                            Recurring.SetDateLastRun(run.GetUpdated());
                            Recurring.SetRunsRemaining(Recurring.GetRunsRemaining() - 1);
                            SetDateNextRun();
                            Recurring.Save(Get_TrxName());
                        }
                        // }
                    }
                }
            }
            DisposeVariables();
            return("");
            //  throw new NotImplementedException();
        }
Example #10
0
        }       //	doIt

        /// <summary>
        /// Create GL Journal
        /// </summary>
        /// <returns>document info</returns>
        private String CreateGLJournal()
        {
            List <X_T_InvoiceGL> list = new List <X_T_InvoiceGL>();
            String sql = "SELECT * FROM T_InvoiceGL "
                         + "WHERE AD_PInstance_ID=" + GetAD_PInstance_ID()
                         + " ORDER BY AD_Org_ID";
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName());
                while (idr.Read())
                {
                    list.Add(new X_T_InvoiceGL(GetCtx(), idr, Get_TrxName()));
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }
            if (list.Count == 0)
            {
                return(" - No Records found");
            }

            //
            MAcctSchema        aas            = MAcctSchema.Get(GetCtx(), _C_AcctSchema_ID);
            MAcctSchemaDefault asDefaultAccts = MAcctSchemaDefault.Get(GetCtx(), _C_AcctSchema_ID);
            MGLCategory        cat            = MGLCategory.GetDefaultSystem(GetCtx());

            if (cat == null)
            {
                MDocType docType = MDocType.Get(GetCtx(), _C_DocTypeReval_ID);
                cat = MGLCategory.Get(GetCtx(), docType.GetGL_Category_ID());
            }
            //
            MJournalBatch batch = new MJournalBatch(GetCtx(), 0, Get_TrxName());

            batch.SetDescription(GetName());
            batch.SetC_DocType_ID(_C_DocTypeReval_ID);
            batch.SetDateDoc(DateTime.Now);// new Timestamp(System.currentTimeMillis()));
            batch.SetDateAcct(_DateReval);
            batch.SetC_Currency_ID(aas.GetC_Currency_ID());
            if (!batch.Save())
            {
                return(GetRetrievedError(batch, "Could not create Batch"));
                //return " - Could not create Batch";
            }
            //
            MJournal journal   = null;
            Decimal? drTotal   = Env.ZERO;
            Decimal? crTotal   = Env.ZERO;
            int      AD_Org_ID = 0;

            for (int i = 0; i < list.Count; i++)
            {
                X_T_InvoiceGL gl = list[i];//.get(i);
                if (Env.Signum(gl.GetAmtRevalDrDiff()) == 0 && Env.Signum(gl.GetAmtRevalCrDiff()) == 0)
                {
                    continue;
                }
                MInvoice invoice = new MInvoice(GetCtx(), gl.GetC_Invoice_ID(), null);
                if (invoice.GetC_Currency_ID() == aas.GetC_Currency_ID())
                {
                    continue;
                }
                //
                if (journal == null)
                {
                    journal = new MJournal(batch);
                    journal.SetC_AcctSchema_ID(aas.GetC_AcctSchema_ID());
                    journal.SetC_Currency_ID(aas.GetC_Currency_ID());
                    journal.SetC_ConversionType_ID(_C_ConversionTypeReval_ID);
                    MOrg org = MOrg.Get(GetCtx(), gl.GetAD_Org_ID());
                    journal.SetDescription(GetName() + " - " + org.GetName());
                    journal.SetGL_Category_ID(cat.GetGL_Category_ID());
                    if (!journal.Save())
                    {
                        return(GetRetrievedError(journal, "Could not create Journal"));
                        //return " - Could not create Journal";
                    }
                }
                //
                MJournalLine line = new MJournalLine(journal);
                line.SetLine((i + 1) * 10);
                line.SetDescription(invoice.GetSummary());
                //
                MFactAcct fa = new MFactAcct(GetCtx(), gl.GetFact_Acct_ID(), null);
                line.SetC_ValidCombination_ID(MAccount.Get(fa));
                Decimal?dr = gl.GetAmtRevalDrDiff();
                Decimal?cr = gl.GetAmtRevalCrDiff();
                drTotal = Decimal.Add(drTotal.Value, dr.Value);
                crTotal = Decimal.Add(crTotal.Value, cr.Value);
                line.SetAmtSourceDr(dr.Value);
                line.SetAmtAcctDr(dr.Value);
                line.SetAmtSourceCr(cr.Value);
                line.SetAmtAcctCr(cr.Value);
                line.Save();
                //
                if (AD_Org_ID == 0)             //	invoice org id
                {
                    AD_Org_ID = gl.GetAD_Org_ID();
                }
                //	Change in Org
                if (AD_Org_ID != gl.GetAD_Org_ID())
                {
                    CreateBalancing(asDefaultAccts, journal, drTotal.Value, crTotal.Value, AD_Org_ID, (i + 1) * 10);
                    //
                    AD_Org_ID = gl.GetAD_Org_ID();
                    drTotal   = Env.ZERO;
                    crTotal   = Env.ZERO;
                    journal   = null;
                }
            }
            CreateBalancing(asDefaultAccts, journal, drTotal.Value, crTotal.Value, AD_Org_ID, (list.Count + 1) * 10);

            return(" - " + batch.GetDocumentNo() + " #" + list.Count);
        }       //	createGLJournal
        /// <summary>
        /// Process
        /// </summary>
        /// <returns></returns>
        protected override string DoIt()
        {
            try
            {
                MRevenueRecognitionPlan revenueRecognitionPlan = null;
                MInvoiceLine            invoiceLine            = null;
                MInvoice            invoice             = null;
                MRevenueRecognition mRevenueRecognition = new MRevenueRecognition(GetCtx(), _RevenueRecognition_ID, Get_Trx());

                // Count of  previous date's RevenueRecognition_Run whose journal is not created
                string sql = "SELECT COUNT(C_RevenueRecognition_Run_ID) FROM C_RevenueRecognition_Run run " +
                             "INNER JOIN C_RevenueRecognition_Plan pl ON pl.C_RevenueRecognition_Plan_ID = run.C_RevenueRecognition_Plan_ID WHERE ";
                if (C_InvoiceLine_ID > 0)
                {
                    sql += "pl.C_invoiceLine_ID = " + C_InvoiceLine_ID + " AND ";
                }

                sql += "pl.C_RevenueRecognition_ID = " + _RevenueRecognition_ID + " AND NVL(GL_Journal_ID, 0)<=0 AND run.RECOGNITIONDATE < " + GlobalVariable.TO_DATE(DateTime.Now, true);

                if (Util.GetValueOfInt(DB.ExecuteScalar(sql)) == 0)
                {
                    MRevenueRecognitionPlan[] revenueRecognitionPlans = MRevenueRecognitionPlan.GetRecognitionPlans(mRevenueRecognition, C_InvoiceLine_ID, _orgId);
                    journal_ID = new int[revenueRecognitionPlans.Length];

                    if (ReversalType == "P")
                    {
                        for (int i = 0; i < revenueRecognitionPlans.Length; i++)
                        {
                            revenueRecognitionPlan = revenueRecognitionPlans[i];
                            invoiceLine            = new MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_Trx());
                            invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_Trx());

                            //get Sum of Amount Whose journal is not yet created
                            sql = "SELECT SUM(run.Recognizedamt) AS TotalRecognizedAmt FROM C_RevenueRecognition_Run run WHERE " +
                                  "C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " AND NVL(GL_Journal_ID,0) <= 0";

                            totalAmt = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                            if (totalAmt != 0)
                            {
                                //if totalAmount is not 0 then only create Journal

                                if (revenueRecognitionPlan.GetC_AcctSchema_ID() != _AcctSchema_ID || revenueRecognitionPlan.GetC_Currency_ID() != _Currency_ID)
                                {
                                    if (journal != null)
                                    {
                                        if (DocNo == null)
                                        {
                                            DocNo = journal.GetDocumentNo();
                                        }
                                        else
                                        {
                                            DocNo += "," + journal.GetDocumentNo();
                                        }
                                        journal_ID[i - 1] = journal.GetGL_Journal_ID();
                                    }
                                    journal = new MJournal(GetCtx(), 0, Get_Trx());

                                    journal.SetC_DocType_ID(_DocType);
                                    journal = CreateJournalHDR(revenueRecognitionPlan);
                                    if (journal.Save(Get_TrxName()))
                                    {
                                        _AcctSchema_ID = journal.GetC_AcctSchema_ID();
                                        _Currency_ID   = journal.GetC_Currency_ID();
                                        lineno         = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(Line), 0)+10  AS DefaultValue FROM GL_JournalLine WHERE GL_Journal_ID=" + journal.GetGL_Journal_ID(), null, invoice.Get_Trx()));
                                    }
                                    else
                                    {
                                        pp = VLogger.RetrieveError();
                                        if (pp != null)
                                        {
                                            errorMsg = pp.GetName();
                                            if (errorMsg == "")
                                            {
                                                errorMsg = pp.GetValue();
                                            }
                                        }
                                        if (errorMsg == "")
                                        {
                                            errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                                        }
                                        Get_TrxName().Rollback();
                                        return(errorMsg);
                                    }
                                }
                                revenueRecognitionPlan.SetRecognizedAmt(totalAmt + revenueRecognitionPlan.GetRecognizedAmt());
                                if (!revenueRecognitionPlan.Save())
                                {
                                    pp = VLogger.RetrieveError();
                                    if (pp != null)
                                    {
                                        errorMsg = pp.GetName();
                                        if (errorMsg == "")
                                        {
                                            errorMsg = pp.GetValue();
                                        }
                                    }
                                    if (errorMsg == "")
                                    {
                                        errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                                    }
                                    Get_TrxName().Rollback();
                                    return(errorMsg);
                                }

                                for (int k = 0; k < 2; k++)
                                {
                                    journalLine = new MJournalLine(journal);

                                    journalLine = GenerateJounalLine(journal, invoice, invoiceLine, revenueRecognitionPlan, totalAmt, mRevenueRecognition.GetRecognitionType(), k);
                                    if (journalLine.Save(Get_TrxName()))
                                    {
                                        lineno += 10;
                                    }
                                    else
                                    {
                                        pp = VLogger.RetrieveError();
                                        if (pp != null)
                                        {
                                            errorMsg = pp.GetName();
                                            if (errorMsg == "")
                                            {
                                                errorMsg = pp.GetValue();
                                            }
                                        }
                                        if (errorMsg == "")
                                        {
                                            errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                                        }
                                        Get_TrxName().Rollback();
                                        return(errorMsg);
                                    }
                                }
                                sql = "UPDATE C_RevenueRecognition_Run  set Gl_Journal_ID= " + journal.GetGL_Journal_ID() +
                                      " WHERE C_RevenueRecognition_Plan_ID= " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + "AND NVL(Gl_Journal_ID,0)=0";
                                int count = DB.ExecuteQuery(sql, null, Get_Trx());
                                log.Log(Level.INFO, (Msg.GetMsg(GetCtx(), "RevenueRecognitionRunUpdated") + count));
                            }
                        }
                        if (journal != null)
                        {
                            if (DocNo == null)
                            {
                                DocNo = journal.GetDocumentNo();
                            }
                            else
                            {
                                DocNo += "," + journal.GetDocumentNo();
                            }
                            journal_ID[journal_ID.Length - 1] = journal.GetGL_Journal_ID();
                        }
                    }
                    #region Existing Reversal Type
                    //else if (ReversalType == "E")
                    //{
                    //    for (int i = 0; i < revenueRecognitionPlans.Length; i++)
                    //    {
                    //        MRevenueRecognitionPlan revenueRecognitionPlan = revenueRecognitionPlans[i];
                    //        MInvoiceLine invoiceLine = new MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_Trx());
                    //        MInvoice invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_Trx());
                    //        sql = "Select Distinct round(SUM(recognizedamt),5) as RecognizedAmt from C_RevenueRecognition_Run Where C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " And NVL(GL_Journal_ID,0) > 0 ";
                    //        DataSet ds = new DataSet();
                    //        ds = DB.ExecuteDataset(sql);
                    //        if (ds != null && ds.Tables[0].Rows.Count > 0)
                    //        {
                    //            decimal Amt = Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["RecognizedAmt"]);
                    //            string sql1 = "Select GL_Journal_ID from C_RevenueRecognition_Run Where C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " And NVL(GL_Journal_ID,0) > 0 AND RowNum=1";
                    //            int GL_Journal_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql1));
                    //            MJournal journal = new MJournal(GetCtx(), GL_Journal_ID, Get_TrxName());
                    //            log.Info(ToString());
                    //            //	Journal
                    //            MJournal reverse = new MJournal(journal);
                    //            reverse.SetDateDoc(DateTime.Now);
                    //            reverse.SetC_Period_ID(journal.GetC_Period_ID());
                    //            int Period_ID = MPeriod.GetC_Period_ID(GetCtx(), DateTime.Now);
                    //            reverse.SetDateAcct(DateTime.Now);
                    //            if (reverse.Save())
                    //            {
                    //                MJournalLine[] journalLines = journal.GetLines(false);
                    //                if (journalLines.Length > 0)
                    //                {
                    //                    for (int j = 0; j < journalLines.Length; j++)
                    //                    {
                    //                        MJournalLine journalLine = journalLines[j];
                    //                        MJournalLine newjournalLine = new MJournalLine(GetCtx(), 0, Get_TrxName());
                    //                        PO.CopyValues(journalLine, newjournalLine, GetAD_Client_ID(), GetAD_Org_ID());
                    //                        newjournalLine.SetGL_Journal_ID(reverse.GetGL_Journal_ID());

                    //                        newjournalLine.SetDateAcct(DateTime.Now);
                    //                        //	Amounts
                    //                        if (newjournalLine.GetAmtAcctCr() > 0)
                    //                        {
                    //                            newjournalLine.SetAmtAcctDr(0);
                    //                            newjournalLine.SetAmtSourceDr(0);
                    //                            newjournalLine.SetAmtSourceCr(Decimal.Negate(Amt));
                    //                            newjournalLine.SetAmtAcctCr(Decimal.Negate(Amt));
                    //                        }
                    //                        else
                    //                        {
                    //                            newjournalLine.SetAmtAcctDr(Decimal.Negate(Amt));
                    //                            newjournalLine.SetAmtSourceDr(Decimal.Negate(Amt));
                    //                            newjournalLine.SetAmtSourceCr(0);
                    //                            newjournalLine.SetAmtAcctCr(0);
                    //                        }

                    //                        newjournalLine.SetIsGenerated(true);
                    //                        newjournalLine.SetProcessed(false);
                    //                        newjournalLine.Save();
                    //                        if (j == 1)
                    //                        {
                    //                            break;
                    //                        }
                    //                    }
                    //                }
                    //            }
                    //            if (reverse != null && reverse.GetDocStatus() != "CO")
                    //            {
                    //                reverse.CompleteIt();
                    //                reverse.SetProcessed(true);
                    //                reverse.SetDocStatus("CO");
                    //                reverse.SetDocAction("CL");
                    //                reverse.Save(Get_TrxName());
                    //                if (DocNo == null)
                    //                {
                    //                    DocNo = reverse.GetDocumentNo();
                    //                }
                    //                int count = Util.GetValueOfInt(DB.ExecuteQuery("Update C_RevenueRecognition_Run Set GL_Journal_ID=null WHere C_RevenueRecognition_Plan_ID=" + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID()));
                    //                int count1 = Util.GetValueOfInt(DB.ExecuteQuery("Update C_RevenueRecognition_Plan Set RecognizedAmt=RecognizedAmt - " + Amt + " WHere C_RevenueRecognition_Plan_ID=" + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID()));
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion

                    Get_TrxName().Commit();
                    if (journal_ID != null)
                    {
                        for (int i = 0; i < journal_ID.Length; i++)
                        {
                            if (journal_ID[i] > 0)
                            {
                                string result = RevenueRun.CompleteOrReverse(GetCtx(), journal_ID[i], 169, "CO");
                                if (!String.IsNullOrEmpty(result))
                                {
                                    journalIDS += ", " + journal_ID[i] + " " + result;
                                }
                            }
                        }
                    }

                    if (DocNo == null)
                    {
                        return(Msg.GetMsg(GetCtx(), "FoundNoRevenueRecognitionPlan"));
                    }
                }
                else
                {
                    return(Msg.GetMsg(GetCtx(), "NotRecoganized"));
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "GLJournalnotallocateddueto") + ex.Message);
                Get_TrxName().Rollback();
                return(ex.Message);
            }

            if (!String.IsNullOrEmpty(journalIDS))
            {
                return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo + ", " + Msg.GetMsg(GetCtx(), "GLJournalNotCompleted") + journalIDS);
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo);
            }
        }
        /// <summary>
        /// Create Gl Journal Line
        /// </summary>
        /// <param name="Journal">GL Journal</param>
        /// <param name="Invoice">Invoice</param>
        /// <param name="InvoiceLine">Invoice Line</param>
        /// <param name="RevenueRecognitionPlan">Revenue Recognition Plan</param>
        /// <param name="TotalAmt">Sum of RecognizeAmt</param>
        /// <param name="RecognitionType">Recognition Type</param>
        /// <param name="k">loop variable</param>
        /// <returns>>Journal line object</returns>
        public MJournalLine GenerateJounalLine(MJournal Journal, MInvoice Invoice, MInvoiceLine InvoiceLine,
                                               MRevenueRecognitionPlan RevenueRecognitionPlan, Decimal TotalAmt, string RecognitionType, int k)
        {
            int combination_ID = 0;

            if (k == 0)
            {
                combination_ID = RevenueRun.GetCombinationID(InvoiceLine.GetM_Product_ID(), InvoiceLine.GetC_Charge_ID(), journal.GetC_AcctSchema_ID(), Invoice.IsSOTrx(), Invoice.IsReturnTrx(), totalAmt, RevenueRecognitionPlan.GetC_RevenueRecognition_ID());
                journalLine.SetLine(lineno);
                if (RecognitionType.Equals("E") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctDr(TotalAmt);
                    journalLine.SetAmtSourceDr(TotalAmt);
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("E") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctCr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctCr(TotalAmt);
                    journalLine.SetAmtSourceCr(TotalAmt);
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctDr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));
                journalLine.Set_ValueNoCheck("Account_ID", account_ID);
                journalLine.Set_ValueNoCheck("C_BPartner_ID", Invoice.GetC_BPartner_ID());
                journalLine.SetAD_OrgTrx_ID(InvoiceLine.Get_ColumnIndex("AD_OrgTrx_ID") > 0 ? InvoiceLine.GetAD_OrgTrx_ID() : Invoice.GetAD_OrgTrx_ID());
                journalLine.Set_ValueNoCheck("C_Project_ID", InvoiceLine.GetC_Project_ID() > 0 ? InvoiceLine.GetC_Project_ID() : Invoice.Get_Value("C_ProjectRef_ID"));
                journalLine.Set_ValueNoCheck("C_Campaign_ID", InvoiceLine.Get_ColumnIndex("C_Campaign_ID") > 0 ? InvoiceLine.GetC_Campaign_ID() : Invoice.GetC_Campaign_ID());
                journalLine.Set_ValueNoCheck("C_Activity_ID", InvoiceLine.Get_ColumnIndex("C_Activity_ID") > 0 ? InvoiceLine.GetC_Activity_ID() : Invoice.GetC_Activity_ID());
                journalLine.Set_ValueNoCheck("M_Product_ID", InvoiceLine.GetM_Product_ID());
            }
            else
            {
                combination_ID = RevenueRun.GetCombinationID(0, 0, RevenueRecognitionPlan.GetC_AcctSchema_ID(), Invoice.IsSOTrx(), Invoice.IsReturnTrx(), totalAmt, RevenueRecognitionPlan.GetC_RevenueRecognition_ID());
                int account_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT Account_ID From C_ValidCombination Where C_ValidCombination_ID=" + combination_ID));

                journalLine = RevenueRun.GetOrCreate(journal, journalLine, InvoiceLine.GetM_Product_ID(), InvoiceLine.GetC_Charge_ID(),
                                                     InvoiceLine.Get_ColumnIndex("C_Campaign_ID") > 0 ? InvoiceLine.GetC_Campaign_ID() : Invoice.GetC_Campaign_ID(),
                                                     account_ID, InvoiceLine.GetC_Project_ID() > 0 ? InvoiceLine.GetC_Project_ID() : Util.GetValueOfInt(Invoice.Get_Value("C_ProjectRef_ID")),
                                                     InvoiceLine.Get_ColumnIndex("C_Activity_ID") > 0 ? InvoiceLine.GetC_Activity_ID() : Invoice.GetC_Activity_ID(), Invoice.GetC_BPartner_ID(),
                                                     Invoice.GetAD_Org_ID(), InvoiceLine.Get_ColumnIndex("AD_OrgTrx_ID") > 0 ? InvoiceLine.GetAD_OrgTrx_ID() : Invoice.GetAD_OrgTrx_ID());

                journalLine.SetLine(lineno);

                if (RecognitionType.Equals("E") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctCr(journalLine.GetAmtAcctCr() + TotalAmt);
                    journalLine.SetAmtSourceCr(journalLine.GetAmtSourceCr() + TotalAmt);
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
                else if (RecognitionType.Equals("E") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctDr(journalLine.GetAmtAcctDr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(journalLine.GetAmtSourceDr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt > 0)
                {
                    journalLine.SetAmtAcctDr(journalLine.GetAmtAcctDr() + TotalAmt);
                    journalLine.SetAmtSourceDr(journalLine.GetAmtSourceDr() + TotalAmt);
                    journalLine.SetAmtSourceCr(0);
                    journalLine.SetAmtAcctCr(0);
                }
                else if (RecognitionType.Equals("R") && TotalAmt < 0)
                {
                    journalLine.SetAmtAcctCr(journalLine.GetAmtAcctCr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceCr(journalLine.GetAmtSourceCr() + Decimal.Negate(TotalAmt));
                    journalLine.SetAmtSourceDr(0);
                    journalLine.SetAmtAcctDr(0);
                }
            }
            return(journalLine);
        }
Example #13
0
        protected override string DoIt()
        {
            try
            {
                _log.Info("Start Imported Data completion for GulfOil : " + System.DateTime.Now);

                #region complete Order Record
                sql.Clear();
                sql.Append("SELECT * FROM C_Order WHERE IsActive = 'Y'   AND DocStatus NOT IN ('CO' , 'CL') ORDER BY dateacct");
                dsRecord = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                dataRow = dsRecord.Tables[0].Select("IsActive = 'Y' ", "dateacct");
                if (dataRow != null && dataRow.Length > 0)
                {
                    ViennaAdvantage.Model.MOrder order = null;

                    message.Clear();
                    notCompletedRecord.Clear();
                    message.Append("Records Of C_Order ");

                    for (int i = 0; i < dataRow.Length; i++)
                    {
                        try
                        {
                            order = new ViennaAdvantage.Model.MOrder(GetCtx(), Util.GetValueOfInt(dataRow[i]["C_Order_ID"]), Get_Trx());
                            order.CompleteIt();
                            if (order.GetDocAction() == "CL")
                            {
                                order.SetDocStatus("CO");
                                order.SetDocAction("CL");
                                if (!order.Save(Get_Trx()))
                                {
                                    notCompletedRecord.Append(order.GetDocumentNo() + " ,");
                                    Get_Trx().Rollback();
                                    ValueNamePair pp = VLogger.RetrieveError();
                                    _log.Info("Error found for saving C_Order Record ID = " + order.GetDocumentNo() +
                                              " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                }
                                else
                                {
                                    Get_Trx().Commit();
                                }
                            }
                            else
                            {
                                notCompletedRecord.Append(order.GetDocumentNo() + " ,");
                                Get_Trx().Rollback();
                                _log.Info("Order not completed for this Record ID = " + order.GetDocumentNo());
                            }
                        }
                        catch { }
                    }

                    if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                    {
                        errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                    }
                }
                #endregion

                #region complete Invoice Record
                sql.Clear();
                sql.Append("SELECT * FROM C_Invoice WHERE IsActive = 'Y'   AND DocStatus NOT IN ('CO' , 'CL') ORDER BY dateacct");
                dsRecord = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                dataRow = dsRecord.Tables[0].Select("IsActive = 'Y' ", "dateacct");
                if (dataRow != null && dataRow.Length > 0)
                {
                    ViennaAdvantage.Model.MInvoice invoice = null;

                    message.Clear();
                    notCompletedRecord.Clear();
                    message.Append("Records Of C_Invoice ");

                    for (int i = 0; i < dataRow.Length; i++)
                    {
                        try
                        {
                            invoice = new ViennaAdvantage.Model.MInvoice(GetCtx(), Util.GetValueOfInt(dataRow[i]["C_Invoice_ID"]), Get_Trx());
                            invoice.CompleteIt();
                            if (invoice.GetDocAction() == "CL")
                            {
                                invoice.SetDocStatus("CO");
                                invoice.SetDocAction("CL");
                                if (!invoice.Save(Get_Trx()))
                                {
                                    notCompletedRecord.Append(invoice.GetDocumentNo() + " ,");
                                    Get_Trx().Rollback();
                                    ValueNamePair pp = VLogger.RetrieveError();
                                    _log.Info("Error found for saving C_Invoice Record ID = " + invoice.GetDocumentNo() +
                                              " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                }
                                else
                                {
                                    Get_Trx().Commit();
                                }
                            }
                            else
                            {
                                notCompletedRecord.Append(invoice.GetDocumentNo() + " ,");
                                Get_Trx().Rollback();
                                _log.Info("Invoice not completed for this Record ID = " + invoice.GetDocumentNo() + " Message- " + invoice.GetProcessMsg());
                            }
                        }
                        catch { }
                    }

                    if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                    {
                        errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                    }
                }
                #endregion

                sql.Clear();
                sql.Append("SELECT * FROM M_InOut WHERE IsActive = 'Y'  AND DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY movementdate");
                dsInOut = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                sql.Clear();
                sql.Append("SELECT * FROM M_Inventory WHERE IsActive = 'Y' AND DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY movementdate");
                dsInventory = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                sql.Clear();
                sql.Append("SELECT * FROM M_Movement WHERE IsActive = 'Y' AND  DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY movementdate");
                dsMovement = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                sql.Clear();
                sql.Append("SELECT * FROM C_Payment WHERE IsActive = 'Y' AND  DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY dateacct");
                dsPayment = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                sql.Clear();
                sql.Append("SELECT * FROM C_Cash WHERE IsActive = 'Y' AND  DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY dateacct");
                dsCashJournal = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                sql.Clear();
                sql.Append("SELECT * FROM GL_Journal  WHERE IsActive = 'Y' AND  DocStatus NOT IN ('CO' , 'CL' , 'RE' , 'VO') ORDER BY dateacct");
                dsGLJournal = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());

                // min date record from the transaction window
                minDateRecord = SerachMinDate();

                int diff = (DateTime.Now - minDateRecord.Value).Days;

                for (int days = 0; days <= diff; days++)
                {
                    if (days != 0)
                    {
                        minDateRecord = minDateRecord.Value.AddDays(1);
                    }

                    try
                    {
                        #region Physical Inventory
                        dataRow = dsInventory.Tables[0].Select("isinternaluse = 'N' AND  movementdate = '" + minDateRecord + "'", "M_Inventory_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            MInventory inventory = null;

                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Physical Inventory ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inventory = new MInventory(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_Inventory_ID"]), Get_Trx());
                                    inventory.CompleteIt();
                                    if (inventory.GetDocAction() == "CL")
                                    {
                                        inventory.SetDocStatus("CO");
                                        inventory.SetDocAction("CL");
                                        if (!inventory.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inventory.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving Physical Inventory Record ID = " + inventory.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inventory.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Physical Inventory not completed for this Record ID = " + inventory.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }

                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region Internal use inventory
                        dataRow = dsInventory.Tables[0].Select("isinternaluse = 'Y' AND  movementdate = '" + minDateRecord + "'", "M_Inventory_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            MInventory inventory = null;

                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Internal use inventory ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inventory = new MInventory(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_Inventory_ID"]), Get_Trx());
                                    inventory.CompleteIt();
                                    if (inventory.GetDocAction() == "CL")
                                    {
                                        inventory.SetDocStatus("CO");
                                        inventory.SetDocAction("CL");
                                        if (!inventory.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inventory.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving Physical Inventory Record ID = " + inventory.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inventory.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Physical Inventory not completed for this Record ID = " + inventory.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region complete material receipt
                        dataRow = dsInOut.Tables[0].Select("IsSoTrx = 'N' AND IsReturnTrx = 'N'  AND DocStatus NOT IN ('CO' , 'CL') AND  DateAcct = '" + minDateRecord + "'", "M_InOut_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of material receipt ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inout = new ViennaAdvantage.Model.MInOut(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_InOut_ID"]), Get_Trx());
                                    inout.CompleteIt();
                                    if (inout.GetDocAction() == "CL")
                                    {
                                        inout.SetDocStatus("CO");
                                        inout.SetDocAction("CL");
                                        if (!inout.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Order Record ID = " + inout.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Material Receipt not completed for this Record ID = " + inout.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region complete Movement Record
                        dataRow = dsMovement.Tables[0].Select("movementdate = '" + minDateRecord + "'", "M_Movement_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            ViennaAdvantage.Model.MMovement movement = null;

                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of M_Movement ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    movement = new ViennaAdvantage.Model.MMovement(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_Movement_ID"]), Get_Trx());
                                    movement.CompleteIt();
                                    if (movement.GetDocAction() == "CL")
                                    {
                                        movement.SetDocStatus("CO");
                                        movement.SetDocAction("CL");
                                        if (!movement.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(movement.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Invoice Record ID = " + movement.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(movement.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Movement not completed for this Record ID = " + movement.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region complete shipment
                        dataRow = dsInOut.Tables[0].Select("IsSoTrx = 'Y' AND IsReturnTrx = 'N' AND  DateAcct = '" + minDateRecord + "'", "M_Inout_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of shipment ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inout = new ViennaAdvantage.Model.MInOut(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_InOut_ID"]), Get_Trx());
                                    inout.CompleteIt();
                                    if (inout.GetDocAction() == "CL")
                                    {
                                        inout.SetDocStatus("CO");
                                        inout.SetDocAction("CL");
                                        if (!inout.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Order Record ID = " + inout.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Shipment not completed for this Record ID = " + inout.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region complete Customer Return
                        dataRow = dsInOut.Tables[0].Select("IsSoTrx = 'Y' AND IsReturnTrx = 'Y'  AND  DateAcct = '" + minDateRecord + "'", "M_Inout_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Customer Return ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inout = new ViennaAdvantage.Model.MInOut(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_InOut_ID"]), Get_Trx());
                                    inout.CompleteIt();
                                    if (inout.GetDocAction() == "CL")
                                    {
                                        inout.SetDocStatus("CO");
                                        inout.SetDocAction("CL");
                                        if (!inout.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Order Record ID = " + inout.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Customer return not completed for this Record ID = " + inout.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region complete Return to Vendor
                        dataRow = dsInOut.Tables[0].Select("IsSoTrx = 'N' AND IsReturnTrx = 'Y'  AND  DateAcct = '" + minDateRecord + "'", "M_InOut_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Return to Vendor ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    inout = new ViennaAdvantage.Model.MInOut(GetCtx(), Util.GetValueOfInt(dataRow[i]["M_InOut_ID"]), Get_Trx());
                                    inout.CompleteIt();
                                    if (inout.GetDocAction() == "CL")
                                    {
                                        inout.SetDocStatus("CO");
                                        inout.SetDocAction("CL");
                                        if (!inout.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Order Record ID = " + inout.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(inout.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Return to Vendor not completed for this Record ID = " + inout.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region Complete Payment
                        dataRow = dsPayment.Tables[0].Select("DateAcct = '" + minDateRecord + "'", "C_Payment_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Payment ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    payment = new MPayment(GetCtx(), Util.GetValueOfInt(dataRow[i]["C_Payment_ID"]), Get_Trx());
                                    payment.CompleteIt();
                                    if (payment.GetDocAction() == "CL")
                                    {
                                        payment.SetDocStatus("CO");
                                        payment.SetDocAction("CL");
                                        if (!payment.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(payment.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Payment Record ID = " + payment.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(payment.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Payment not completed for this Record ID = " + payment.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region Complete Cash Journal
                        dataRow = dsCashJournal.Tables[0].Select("DateAcct = '" + minDateRecord + "'", "C_Cash_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of Cash Journal ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    cash = new MCash(GetCtx(), Util.GetValueOfInt(dataRow[i]["C_Cash_ID"]), Get_Trx());
                                    cash.CompleteIt();
                                    if (cash.GetDocAction() == "CL")
                                    {
                                        cash.SetDocStatus("CO");
                                        cash.SetDocAction("CL");
                                        if (!cash.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(cash.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Cash Record ID = " + cash.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(cash.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Cash Journal not completed for this Record ID = " + cash.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion

                        #region Complete GL Journal
                        dataRow = dsGLJournal.Tables[0].Select("DateAcct = '" + minDateRecord + "'", "GL_Journal_ID");
                        if (dataRow != null && dataRow.Length > 0)
                        {
                            message.Clear();
                            notCompletedRecord.Clear();
                            message.Append("Records Of GL Journal ");

                            for (int i = 0; i < dataRow.Length; i++)
                            {
                                try
                                {
                                    journal = new MJournal(GetCtx(), Util.GetValueOfInt(dataRow[i]["GL_Journal_ID"]), Get_Trx());
                                    journal.CompleteIt();
                                    if (journal.GetDocAction() == "CL")
                                    {
                                        journal.SetDocStatus("CO");
                                        journal.SetDocAction("CL");
                                        if (!journal.Save(Get_Trx()))
                                        {
                                            notCompletedRecord.Append(journal.GetDocumentNo() + " ,");
                                            Get_Trx().Rollback();
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            _log.Info("Error found for saving C_Cash Record ID = " + journal.GetDocumentNo() +
                                                      " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                                        }
                                        else
                                        {
                                            Get_Trx().Commit();
                                        }
                                    }
                                    else
                                    {
                                        notCompletedRecord.Append(journal.GetDocumentNo() + " ,");
                                        Get_Trx().Rollback();
                                        _log.Info("Cash Journal not completed for this Record ID = " + journal.GetDocumentNo());
                                    }
                                }
                                catch { }
                            }
                            if (!string.IsNullOrEmpty(notCompletedRecord.ToString()))
                            {
                                errorMessage.Append(message.ToString() + " : " + notCompletedRecord.ToString());
                            }
                        }
                        #endregion
                    }
                    catch { }
                }
                _log.Info(" End Imported Data completion for GulfOil : " + System.DateTime.Now);
            }
            catch (Exception ex)
            {
                _log.Info("Error Occured during completion of record by using  ImportedDataCompletion Process - " + ex.ToString());
                return(Msg.GetMsg(GetCtx(), "NotCompleted"));
            }
            if (!string.IsNullOrEmpty(errorMessage.ToString()))
            {
                return("Not Completed Record : " + errorMessage.ToString());
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "SucessfullyCompleted"));
            }
        }
        /// <summary>
        /// Create GL Journal
        /// </summary>
        /// <param name="mRevenueRecognition">Revenue Recognition</param>
        /// <returns>Message</returns>
        public string CreateJournals(MRevenueRecognition mRevenueRecognition)
        {
            try
            {
                MRevenueRecognitionRun[] mRevenueRecognitionRuns = null;

                MRevenueRecognitionPlan revenueRecognitionPlan = null;
                MInvoiceLine            invoiceLine            = null;
                MInvoice invoice = null;


                mRevenueRecognitionRuns = MRevenueRecognitionRun.GetRecognitionRuns(mRevenueRecognition, _RecognitionDate, _orgId, false);
                journal_ID = new int[mRevenueRecognitionRuns.Length];
                if (mRevenueRecognitionRuns.Length > 0)
                {
                    for (int j = 0; j < mRevenueRecognitionRuns.Length; j++)
                    {
                        MRevenueRecognitionRun revenueRecognitionRun = mRevenueRecognitionRuns[j];
                        revenueRecognitionPlan = new MRevenueRecognitionPlan(GetCtx(), revenueRecognitionRun.GetC_RevenueRecognition_Plan_ID(), Get_TrxName());
                        invoiceLine            = new MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_TrxName());
                        invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_TrxName());

                        if (revenueRecognitionPlan.GetC_AcctSchema_ID() != _AcctSchema_ID || revenueRecognitionPlan.GetC_Currency_ID() != _Currency_ID || revenueRecognitionRun.GetRecognitionDate() != _RecognizeDate)
                        {
                            if (journal != null)
                            {
                                if (DocNo == null)
                                {
                                    DocNo = journal.GetDocumentNo();
                                }
                                else
                                {
                                    DocNo += ", " + journal.GetDocumentNo();
                                }
                                journal_ID[j - 1] = journal.GetGL_Journal_ID();
                            }
                            journal = new MJournal(GetCtx(), 0, Get_TrxName());

                            journal.SetC_DocType_ID(_DocType);
                            journal = CreateJournalHDR(revenueRecognitionPlan, revenueRecognitionRun, mRevenueRecognition.GetRecognitionFrequency());


                            if (journal.Save())
                            {
                                _AcctSchema_ID = journal.GetC_AcctSchema_ID();
                                _Currency_ID   = journal.GetC_Currency_ID();
                                _RecognizeDate = revenueRecognitionRun.GetRecognitionDate();
                                lineno         = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(Line), 0)+10  AS DefaultValue FROM GL_JournalLine WHERE GL_Journal_ID=" + journal.GetGL_Journal_ID(), null, invoice.Get_Trx()));
                            }
                            else
                            {
                                pp = VLogger.RetrieveError();
                                if (pp != null)
                                {
                                    errorMsg = pp.GetName();
                                    if (errorMsg == "")
                                    {
                                        errorMsg = pp.GetValue();
                                    }
                                }
                                if (errorMsg == "")
                                {
                                    errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                                }
                                Get_TrxName().Rollback();
                                return(errorMsg);
                            }
                        }
                        for (int k = 0; k < 2; k++)
                        {
                            journalLine = new MJournalLine(journal);
                            journalLine = GenerateJounalLine(journal, invoice, invoiceLine, revenueRecognitionPlan, revenueRecognitionRun, mRevenueRecognition.GetRecognitionType(), k);
                            if (journalLine.Save())
                            {
                                revenueRecognitionRun.SetGL_Journal_ID(journal.GetGL_Journal_ID());
                                revenueRecognitionRun.Save();
                                lineno += 10;
                            }
                            else
                            {
                                pp = VLogger.RetrieveError();
                                if (pp != null)
                                {
                                    errorMsg = pp.GetName();
                                    if (errorMsg == "")
                                    {
                                        errorMsg = pp.GetValue();
                                    }
                                }
                                if (errorMsg == "")
                                {
                                    errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                                }
                                Get_TrxName().Rollback();
                                return(errorMsg);
                            }
                        }
                        revenueRecognitionPlan.SetRecognizedAmt(revenueRecognitionRun.GetRecognizedAmt() + revenueRecognitionPlan.GetRecognizedAmt());
                        if (!revenueRecognitionPlan.Save())
                        {
                            pp = VLogger.RetrieveError();
                            if (pp != null)
                            {
                                errorMsg = pp.GetName();
                                if (errorMsg == "")
                                {
                                    errorMsg = pp.GetValue();
                                }
                            }
                            if (errorMsg == "")
                            {
                                errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated");
                            }
                            Get_TrxName().Rollback();
                            return(errorMsg);
                        }
                    }
                    if (journal != null)
                    {
                        if (DocNo == null)
                        {
                            DocNo = journal.GetDocumentNo();
                        }
                        else
                        {
                            DocNo += ", " + journal.GetDocumentNo();
                        }

                        journal_ID[journal_ID.Length - 1] = journal.GetGL_Journal_ID();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "GLJournalnotallocateddueto") + ex.Message);
                Get_TrxName().Rollback();
                return(ex.Message);
            }
            if (DocNo == null)
            {
                return(Msg.GetMsg(GetCtx(), "FoundNoRevenueRecognitionPlan"));
            }

            Get_TrxName().Commit();
            if (journal_ID != null)
            {
                for (int i = 0; i < journal_ID.Length; i++)
                {
                    if (journal_ID[i] > 0)
                    {
                        string result = CompleteOrReverse(GetCtx(), journal_ID[i], 169, "CO");
                        if (!String.IsNullOrEmpty(result))
                        {
                            journalIDS += ", " + journal_ID[i] + " " + result;
                        }
                    }
                }
            }
            if (!String.IsNullOrEmpty(journalIDS))
            {
                return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo + " " + Msg.GetMsg(GetCtx(), "GLJournalNotCompleted") + journalIDS);
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo);
            }
        }
Example #15
0
        }       //	prepare

        /// <summary>
        /// Perrform Process.
        /// </summary>
        /// <returns>message</returns>
        protected override String DoIt()
        {
            log.Info("IsValidateOnly=" + _IsValidateOnly + ", IsImportOnlyNoErrors=" + _IsImportOnlyNoErrors);
            StringBuilder sql         = null;
            int           no          = 0;
            String        clientCheck = " AND AD_Client_ID=" + _AD_Client_ID;

            //	****	Prepare	****

            //	Delete Old Imported
            if (_DeleteOldImported)
            {
                sql = new StringBuilder("DELETE FROM I_GLJournal "
                                        + "WHERE I_IsImported='Y'").Append(clientCheck);
                no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                log.Fine("Delete Old Impored =" + no);
            }

            //	Set IsActive, Created/Updated
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET IsActive = COALESCE (IsActive, 'Y'),"
                                    + " Created = COALESCE (Created, SysDate),"
                                    + " CreatedBy = COALESCE (CreatedBy, 0),"
                                    + " Updated = COALESCE (Updated, SysDate),"
                                    + " UpdatedBy = COALESCE (UpdatedBy, 0),"
                                    + " I_ErrorMsg = NULL,"
                                    + " I_IsImported = 'N' "
                                    + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Info("Reset=" + no);

            //	Set Client from Name
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET AD_Client_ID=(SELECT c.AD_Client_ID FROM AD_Client c WHERE c.Value=i.ClientValue) "
                                    + "WHERE (AD_Client_ID IS NULL OR AD_Client_ID=0) AND ClientValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'");
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Client from Value=" + no);

            //	Set Default Client, Doc Org, AcctSchema, DatAcct
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET AD_Client_ID = COALESCE (AD_Client_ID,").Append(_AD_Client_ID).Append("),"
                                                                                                                 + " AD_OrgDoc_ID = COALESCE (AD_OrgDoc_ID,").Append(_AD_Org_ID).Append("),");
            if (_C_AcctSchema_ID != 0)
            {
                sql.Append(" C_AcctSchema_ID = COALESCE (C_AcctSchema_ID,").Append(_C_AcctSchema_ID).Append("),");
            }
            if (_DateAcct != null)
            {
                sql.Append(" DateAcct = COALESCE (DateAcct,").Append(DataBase.DB.TO_DATE(_DateAcct)).Append("),");
            }
            sql.Append(" Updated = COALESCE (Updated, SysDate) "
                       + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Client/DocOrg/Default=" + no);

            //	Error Doc Org
            String ts = DataBase.DB.IsPostgreSQL() ? "COALESCE(I_ErrorMsg,'')" : "I_ErrorMsg";  //java bug, it could not be used directly

            sql = new StringBuilder("UPDATE I_GLJournal o "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Doc Org, '"
                                    + "WHERE (AD_OrgDoc_ID IS NULL OR AD_OrgDoc_ID=0"
                                    + " OR EXISTS (SELECT * FROM AD_Org oo WHERE o.AD_Org_ID=oo.AD_Org_ID AND (oo.IsSummary='Y' OR oo.IsActive='N')))"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Doc Org=" + no);
            }

            //	Set AcctSchema
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_AcctSchema_ID=(SELECT a.C_AcctSchema_ID FROM C_AcctSchema a"
                                    + " WHERE i.AcctSchemaName=a.Name AND i.AD_Client_ID=a.AD_Client_ID) "
                                    + "WHERE C_AcctSchema_ID IS NULL AND AcctSchemaName IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set AcctSchema from Name=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_AcctSchema_ID=(SELECT c.C_AcctSchema1_ID FROM AD_ClientInfo c WHERE c.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE C_AcctSchema_ID IS NULL AND AcctSchemaName IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set AcctSchema from Client=" + no);
            //	Error AcctSchema
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid AcctSchema, '"
                                    + "WHERE (C_AcctSchema_ID IS NULL OR C_AcctSchema_ID=0"
                                    + " OR NOT EXISTS (SELECT * FROM C_AcctSchema a WHERE i.AD_Client_ID=a.AD_Client_ID))"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid AcctSchema=" + no);
            }

            //	Set DateAcct (mandatory)
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET DateAcct=SysDate "
                                    + "WHERE DateAcct IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set DateAcct=" + no);

            //	Document Type
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_DocType_ID=(SELECT d.C_DocType_ID FROM C_DocType d"
                                    + " WHERE d.Name=i.DocTypeName AND d.DocBaseType='GLJ' AND i.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND DocTypeName IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set DocType=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid DocType, '"
                                    + "WHERE (C_DocType_ID IS NULL OR C_DocType_ID=0"
                                    + " OR NOT EXISTS (SELECT * FROM C_DocType d WHERE i.AD_Client_ID=d.AD_Client_ID AND d.DocBaseType='GLJ'))"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid DocType=" + no);
            }

            //	GL Category
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET GL_Category_ID=(SELECT c.GL_Category_ID FROM GL_Category c"
                                    + " WHERE c.Name=i.CategoryName AND i.AD_Client_ID=c.AD_Client_ID) "
                                    + "WHERE GL_Category_ID IS NULL AND CategoryName IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set DocType=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Category, '"
                                    + "WHERE (GL_Category_ID IS NULL OR GL_Category_ID=0)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Category=" + no);
            }

            //	Set Currency
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_Currency_ID=(SELECT c.C_Currency_ID FROM C_Currency c"
                                    + " WHERE c.ISO_Code=i.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) "
                                    + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Currency from ISO=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_Currency_ID=(SELECT a.C_Currency_ID FROM C_AcctSchema a"
                                    + " WHERE a.C_AcctSchema_ID=i.C_AcctSchema_ID AND a.AD_Client_ID=i.AD_Client_ID)"
                                    + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Default Currency=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Currency, '"
                                    + "WHERE (C_Currency_ID IS NULL OR C_Currency_ID=0)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Currency=" + no);
            }

            //	Set Conversion Type
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET ConversionTypeValue='S' "
                                    + "WHERE C_ConversionType_ID IS NULL AND ConversionTypeValue IS NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set CurrencyType Value to Spot =" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_ConversionType_ID=(SELECT c.C_ConversionType_ID FROM C_ConversionType c"
                                    + " WHERE c.Value=i.ConversionTypeValue AND c.AD_Client_ID IN (0,i.AD_Client_ID)) "
                                    + "WHERE C_ConversionType_ID IS NULL AND ConversionTypeValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set CurrencyType from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid CurrencyType, '"
                                    + "WHERE (C_ConversionType_ID IS NULL OR C_ConversionType_ID=0) AND ConversionTypeValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid CurrencyTypeValue=" + no);
            }


            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No ConversionType, '"
                                    + "WHERE (C_ConversionType_ID IS NULL OR C_ConversionType_ID=0)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No CourrencyType=" + no);
            }

            //	Set/Overwrite Home Currency Rate
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET CurrencyRate=1"
                                    + "WHERE EXISTS (SELECT * FROM C_AcctSchema a"
                                    + " WHERE a.C_AcctSchema_ID=i.C_AcctSchema_ID AND a.C_Currency_ID=i.C_Currency_ID)"
                                    + " AND C_Currency_ID IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Home CurrencyRate=" + no);
            //	Set Currency Rate
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET CurrencyRate=(SELECT MAX(r.MultiplyRate) FROM C_Conversion_Rate r, C_AcctSchema s"
                                    + " WHERE s.C_AcctSchema_ID=i.C_AcctSchema_ID AND s.AD_Client_ID=i.AD_Client_ID"
                                    + " AND r.C_Currency_ID=i.C_Currency_ID AND r.C_Currency_ID_TO=s.C_Currency_ID"
                                    + " AND r.AD_Client_ID=i.AD_Client_ID AND r.AD_Org_ID=i.AD_OrgDoc_ID"
                                    + " AND r.C_ConversionType_ID=i.C_ConversionType_ID"
                                    + " AND i.DateAcct BETWEEN r.ValidFrom AND r.ValidTo "
                                    //	ORDER BY ValidFrom DESC
                                    + ") WHERE CurrencyRate IS NULL OR CurrencyRate=0 AND C_Currency_ID>0"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Org Rate=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET CurrencyRate=(SELECT MAX(r.MultiplyRate) FROM C_Conversion_Rate r, C_AcctSchema s"
                                    + " WHERE s.C_AcctSchema_ID=i.C_AcctSchema_ID AND s.AD_Client_ID=i.AD_Client_ID"
                                    + " AND r.C_Currency_ID=i.C_Currency_ID AND r.C_Currency_ID_TO=s.C_Currency_ID"
                                    + " AND r.AD_Client_ID=i.AD_Client_ID"
                                    + " AND r.C_ConversionType_ID=i.C_ConversionType_ID"
                                    + " AND i.DateAcct BETWEEN r.ValidFrom AND r.ValidTo "
                                    //	ORDER BY ValidFrom DESC
                                    + ") WHERE CurrencyRate IS NULL OR CurrencyRate=0 AND C_Currency_ID>0"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Client Rate=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No Rate, '"
                                    + "WHERE CurrencyRate IS NULL OR CurrencyRate=0"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No Rate=" + no);
            }

            //	Set Period
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_Period_ID=(SELECT MAX(p.C_Period_ID) FROM C_Period p"
                                    + " INNER JOIN C_Year y ON (y.C_Year_ID=p.C_Year_ID)"
                                    + " INNER JOIN AD_ClientInfo c ON (c.C_Calendar_ID=y.C_Calendar_ID)"
                                    + " WHERE c.AD_Client_ID=i.AD_Client_ID"
                                    + " AND i.DateAcct BETWEEN p.StartDate AND p.EndDate AND p.PeriodType='S') "
                                    + "WHERE C_Period_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Period=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Period, '"
                                    + "WHERE C_Period_ID IS NULL OR C_Period_ID NOt IN "
                                    + "(SELECT C_Period_ID FROM C_Period p"
                                    + " INNER JOIN C_Year y ON (y.C_Year_ID=p.C_Year_ID)"
                                    + " INNER JOIN AD_ClientInfo c ON (c.C_Calendar_ID=y.C_Calendar_ID) "
                                    + " WHERE c.AD_Client_ID=i.AD_Client_ID"
                                    + " AND i.DateAcct BETWEEN p.StartDate AND p.EndDate AND p.PeriodType='S')"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Period=" + no);
            }
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_ErrorMsg=" + ts + "||'WARN=Period Closed, ' "
                                    + "WHERE C_Period_ID IS NOT NULL AND NOT EXISTS"
                                    + " (SELECT * FROM C_PeriodControl pc WHERE pc.C_Period_ID=i.C_Period_ID AND DocBaseType='GLJ' AND PeriodStatus='O') "
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Period Closed=" + no);
            }

            //	Posting Type
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET PostingType='A' "
                                    + "WHERE PostingType IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Actual PostingType=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid PostingType, ' "
                                    + "WHERE PostingType IS NULL OR NOT EXISTS"
                                    + " (SELECT * FROM AD_Ref_List r WHERE r.AD_Reference_ID=125 AND i.PostingType=r.Value)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid PostingTypee=" + no);
            }


            //	** Account Elements (optional) **
            //	(C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0)

            //	Set Org from Name (* is overwritten and default)
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET AD_Org_ID=(SELECT o.AD_Org_ID FROM AD_Org o"
                                    + " WHERE o.Value=i.OrgValue AND o.IsSummary='N' AND i.AD_Client_ID=o.AD_Client_ID) "
                                    + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0) AND OrgValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'");
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Org from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET AD_Org_ID=AD_OrgDoc_ID "
                                    + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0) AND OrgValue IS NULL AND AD_OrgDoc_ID IS NOT NULL AND AD_OrgDoc_ID<>0"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Org from Doc Org=" + no);
            //	Error Org
            sql = new StringBuilder("UPDATE I_GLJournal o "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Org, '"
                                    + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0"
                                    + " OR EXISTS (SELECT * FROM AD_Org oo WHERE o.AD_Org_ID=oo.AD_Org_ID AND (oo.IsSummary='Y' OR oo.IsActive='N')))"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Org=" + no);
            }

            //	Set Account
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET Account_ID=(SELECT MAX(ev.C_ElementValue_ID) FROM C_ElementValue ev"
                                    + " INNER JOIN C_Element e ON (e.C_Element_ID=ev.C_Element_ID)"
                                    + " INNER JOIN C_AcctSchema_Element ase ON (e.C_Element_ID=ase.C_Element_ID AND ase.ElementType='AC')"
                                    + " WHERE ev.Value=i.AccountValue AND ev.IsSummary='N'"
                                    + " AND i.C_AcctSchema_ID=ase.C_AcctSchema_ID AND i.AD_Client_ID=ev.AD_Client_ID) "
                                    + "WHERE Account_ID IS NULL AND AccountValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Account from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Account, '"
                                    + "WHERE (Account_ID IS NULL OR Account_ID=0)"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Account=" + no);
            }

            //	Set BPartner
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_BPartner_ID=(SELECT bp.C_BPartner_ID FROM C_BPartner bp"
                                    + " WHERE bp.Value=i.BPartnerValue AND bp.IsSummary='N' AND i.AD_Client_ID=bp.AD_Client_ID) "
                                    + "WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set BPartner from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid BPartner, '"
                                    + "WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid BPartner=" + no);
            }

            //	Set Product
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET M_Product_ID=(SELECT MAX(p.M_Product_ID) FROM M_Product p"
                                    + " WHERE (p.Value=i.ProductValue OR p.UPC=i.UPC OR p.SKU=i.SKU)"
                                    + " AND p.IsSummary='N' AND i.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_Product_ID IS NULL AND (ProductValue IS NOT NULL OR UPC IS NOT NULL OR SKU IS NOT NULL)"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Product from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Product, '"
                                    + "WHERE M_Product_ID IS NULL AND (ProductValue IS NOT NULL OR UPC IS NOT NULL OR SKU IS NOT NULL)"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Product=" + no);
            }

            //	Set Project
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET C_Project_ID=(SELECT p.C_Project_ID FROM C_Project p"
                                    + " WHERE p.Value=i.ProjectValue AND p.IsSummary='N' AND i.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE C_Project_ID IS NULL AND ProjectValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Project from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Project, '"
                                    + "WHERE C_Project_ID IS NULL AND ProjectValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Project=" + no);
            }

            //	Set TrxOrg
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET AD_OrgTrx_ID=(SELECT o.AD_Org_ID FROM AD_Org o"
                                    + " WHERE o.Value=i.OrgValue AND o.IsSummary='N' AND i.AD_Client_ID=o.AD_Client_ID) "
                                    + "WHERE AD_OrgTrx_ID IS NULL AND OrgTrxValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set OrgTrx from Value=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid OrgTrx, '"
                                    + "WHERE AD_OrgTrx_ID IS NULL AND OrgTrxValue IS NOT NULL"
                                    + " AND (C_ValidCombination_ID IS NULL OR C_ValidCombination_ID=0) AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid OrgTrx=" + no);
            }


            //	Source Amounts
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET AmtSourceDr = 0 "
                                    + "WHERE AmtSourceDr IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set 0 Source Dr=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET AmtSourceCr = 0 "
                                    + "WHERE AmtSourceCr IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set 0 Source Cr=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_ErrorMsg=" + ts + "||'WARN=Zero Source Balance, ' "
                                    + "WHERE (AmtSourceDr-AmtSourceCr)=0"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Zero Source Balance=" + no);
            }

            //	Accounted Amounts (Only if No Error)
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET AmtAcctDr = ROUND(AmtSourceDr * CurrencyRate, 2) " //	HARDCODED rounding
                                    + "WHERE AmtAcctDr IS NULL OR AmtAcctDr=0"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Calculate Acct Dr=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET AmtAcctCr = ROUND(AmtSourceCr * CurrencyRate, 2) "
                                    + "WHERE AmtAcctCr IS NULL OR AmtAcctCr=0"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Calculate Acct Cr=" + no);
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_ErrorMsg=" + ts + "||'WARN=Zero Acct Balance, ' "
                                    + "WHERE (AmtSourceDr-AmtSourceCr)<>0 AND (AmtAcctDr-AmtAcctCr)=0"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Zero Acct Balance=" + no);
            }
            sql = new StringBuilder("UPDATE I_GLJournal i "
                                    + "SET I_ErrorMsg=" + ts + "||'WARN=Check Acct Balance, ' "
                                    + "WHERE ABS(AmtAcctDr-AmtAcctCr)>100000000" //	100 mio
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Chack Acct Balance=" + no);
            }


            /*********************************************************************/

            //	Get Balance
            sql = new StringBuilder("SELECT SUM(AmtSourceDr)-SUM(AmtSourceCr), SUM(AmtAcctDr)-SUM(AmtAcctCr) "
                                    + "FROM I_GLJournal "
                                    + "WHERE I_IsImported='N'").Append(clientCheck);
            IDataReader idr = null;

            try
            {
                //pstmt = DataBase.prepareStatement (sql.ToString(), get_TrxName());
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                if (idr.Read())
                {
                    Decimal?source = Utility.Util.GetValueOfDecimal(idr[0]); // rs.getBigDecimal(1);
                    Decimal?acct   = Utility.Util.GetValueOfDecimal(idr[1]); // rs.getBigDecimal(2);
                    if (Env.Signum(source.Value) == 0 &&
                        acct != null && Env.Signum(acct.Value) == 0)
                    {
                        log.Info("Import Balance = 0");
                    }
                    else
                    {
                        log.Warning("Balance Source=" + source.Value + ", Acct=" + acct.Value);
                    }
                    if (source != null)
                    {
                        AddLog(0, null, source, "@AmtSourceDr@ - @AmtSourceCr@");
                    }
                    if (acct != null)
                    {
                        AddLog(0, null, acct, "@AmtAcctDr@ - @AmtAcctCr@");
                    }
                }
                idr.Close();
            }
            catch (Exception ex)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), ex);
            }

            //	Count Errors
            int errors = DataBase.DB.GetSQLValue(Get_TrxName(),
                                                 "SELECT COUNT(*) FROM I_GLJournal WHERE I_IsImported NOT IN ('Y','N')" + clientCheck);

            if (errors != 0)
            {
                if (_IsValidateOnly || _IsImportOnlyNoErrors)
                {
                    throw new Exception("@Errors@=" + errors);
                }
            }
            else if (_IsValidateOnly)
            {
                return("@Errors@=" + errors);
            }

            log.Info("Validation Errors=" + errors);
            Commit();

            /*********************************************************************/

            int noInsert        = 0;
            int noInsertJournal = 0;
            int noInsertLine    = 0;

            MJournalBatch batch             = null; //	Change Batch per Batch DocumentNo
            String        BatchDocumentNo   = "";
            MJournal      journal           = null;
            String        JournalDocumentNo = "";
            DateTime?     DateAcct          = null;

            //	Go through Journal Records
            sql = new StringBuilder("SELECT * FROM I_GLJournal "
                                    + "WHERE I_IsImported='N'").Append(clientCheck)
                  .Append(" ORDER BY COALESCE(BatchDocumentNo, TO_NCHAR(I_GLJournal_ID)),	COALESCE(JournalDocumentNo, TO_NCHAR(I_GLJournal_ID)), C_AcctSchema_ID, PostingType, C_DocType_ID, GL_Category_ID, C_Currency_ID, TRUNC(DateAcct,'DD'), Line, I_GLJournal_ID");
            try
            {
                //pstmt = DataBase.prepareStatement (sql.ToString (), get_TrxName());
                //ResultSet rs = pstmt.executeQuery ();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                while (idr.Read())
                {
                    X_I_GLJournal imp = new X_I_GLJournal(GetCtx(), idr, Get_TrxName());

                    //	New Batch if Batch Document No changes
                    String impBatchDocumentNo = imp.GetBatchDocumentNo();
                    if (impBatchDocumentNo == null)
                    {
                        impBatchDocumentNo = "";
                    }
                    if (batch == null ||
                        imp.IsCreateNewBatch() ||
                        journal.GetC_AcctSchema_ID() != imp.GetC_AcctSchema_ID() ||
                        !BatchDocumentNo.Equals(impBatchDocumentNo))
                    {
                        BatchDocumentNo = impBatchDocumentNo;   //	cannot compare real DocumentNo
                        batch           = new MJournalBatch(GetCtx(), 0, null);
                        batch.SetClientOrg(imp.GetAD_Client_ID(), imp.GetAD_OrgDoc_ID());
                        if (imp.GetBatchDocumentNo() != null &&
                            imp.GetBatchDocumentNo().Length > 0)
                        {
                            batch.SetDocumentNo(imp.GetBatchDocumentNo());
                        }
                        batch.SetC_DocType_ID(imp.GetC_DocType_ID());
                        batch.SetPostingType(imp.GetPostingType());
                        String description = imp.GetBatchDescription();
                        if (description == null || description.Length == 0)
                        {
                            description = "*Import-";
                        }
                        else
                        {
                            description += " *Import-";
                        }
                        description += DateTime.Now; //new Timestamp(System.currentTimeMillis());
                        batch.SetDescription(description);
                        if (!batch.Save())
                        {
                            log.Log(Level.SEVERE, "Batch not saved");
                            Exception ex = VLogger.RetrieveException();
                            if (ex != null)
                            {
                                AddLog(0, null, null, ex.Message);
                                if (idr != null)
                                {
                                    idr.Close();
                                }
                                throw ex;
                            }
                            break;
                        }
                        noInsert++;
                        journal = null;
                    }
                    //	Journal
                    String impJournalDocumentNo = imp.GetJournalDocumentNo();
                    if (impJournalDocumentNo == null)
                    {
                        impJournalDocumentNo = "";
                    }
                    DateTime?impDateAcct = TimeUtil.GetDay(imp.GetDateAcct());
                    if (journal == null ||
                        imp.IsCreateNewJournal() ||
                        !JournalDocumentNo.Equals(impJournalDocumentNo) ||
                        journal.GetC_DocType_ID() != imp.GetC_DocType_ID() ||
                        journal.GetGL_Category_ID() != imp.GetGL_Category_ID() ||
                        !journal.GetPostingType().Equals(imp.GetPostingType()) ||
                        journal.GetC_Currency_ID() != imp.GetC_Currency_ID() ||
                        !impDateAcct.Equals(DateAcct)
                        )
                    {
                        JournalDocumentNo = impJournalDocumentNo;       //	cannot compare real DocumentNo
                        DateAcct          = impDateAcct.Value;
                        journal           = new MJournal(GetCtx(), 0, Get_TrxName());
                        journal.SetGL_JournalBatch_ID(batch.GetGL_JournalBatch_ID());
                        journal.SetClientOrg(imp.GetAD_Client_ID(), imp.GetAD_OrgDoc_ID());
                        //
                        String description = imp.GetBatchDescription();
                        if (description == null || description.Length == 0)
                        {
                            description = "(Import)";
                        }
                        journal.SetDescription(description);
                        if (imp.GetJournalDocumentNo() != null && imp.GetJournalDocumentNo().Length > 0)
                        {
                            journal.SetDocumentNo(imp.GetJournalDocumentNo());
                        }
                        //
                        journal.SetC_AcctSchema_ID(imp.GetC_AcctSchema_ID());
                        journal.SetC_DocType_ID(imp.GetC_DocType_ID());
                        journal.SetGL_Category_ID(imp.GetGL_Category_ID());
                        journal.SetPostingType(imp.GetPostingType());
                        journal.SetGL_Budget_ID(imp.GetGL_Budget_ID());
                        //
                        journal.SetCurrency(imp.GetC_Currency_ID(), imp.GetC_ConversionType_ID(), imp.GetCurrencyRate());
                        //
                        journal.SetC_Period_ID(imp.GetC_Period_ID());
                        journal.SetDateAcct(imp.GetDateAcct());         //	sets Period if not defined
                        journal.SetDateDoc(imp.GetDateAcct());
                        //
                        if (!journal.Save())
                        {
                            log.Log(Level.SEVERE, "Journal not saved");
                            Exception ex = VLogger.RetrieveException();
                            if (ex != null)
                            {
                                AddLog(0, null, null, ex.Message);
                                if (idr != null)
                                {
                                    idr.Close();
                                }
                                throw ex;
                            }
                            break;
                        }
                        noInsertJournal++;
                    }

                    //	Lines
                    MJournalLine line = new MJournalLine(journal);
                    //
                    line.SetDescription(imp.GetDescription());
                    line.SetCurrency(imp.GetC_Currency_ID(), imp.GetC_ConversionType_ID(), imp.GetCurrencyRate());
                    //	Set/Get Account Combination
                    if (imp.GetC_ValidCombination_ID() == 0)
                    {
                        MAccount acct = MAccount.Get(GetCtx(), imp.GetAD_Client_ID(), imp.GetAD_Org_ID(),
                                                     imp.GetC_AcctSchema_ID(), imp.GetAccount_ID(), 0,
                                                     imp.GetM_Product_ID(), imp.GetC_BPartner_ID(), imp.GetAD_OrgTrx_ID(),
                                                     imp.GetC_LocFrom_ID(), imp.GetC_LocTo_ID(), imp.GetC_SalesRegion_ID(),
                                                     imp.GetC_Project_ID(), imp.GetC_Campaign_ID(), imp.GetC_Activity_ID(),
                                                     imp.GetUser1_ID(), imp.GetUser2_ID(), 0, 0);
                        if (acct != null && acct.Get_ID() == 0)
                        {
                            acct.Save();
                        }
                        if (acct == null || acct.Get_ID() == 0)
                        {
                            imp.SetI_ErrorMsg("ERROR creating Account");
                            imp.SetI_IsImported(X_I_GLJournal.I_ISIMPORTED_No);
                            imp.Save();
                            continue;
                        }
                        else
                        {
                            line.SetC_ValidCombination_ID(acct.Get_ID());
                            imp.SetC_ValidCombination_ID(acct.Get_ID());
                        }
                    }
                    else
                    {
                        line.SetC_ValidCombination_ID(imp.GetC_ValidCombination_ID());
                    }
                    //
                    line.SetLine(imp.GetLine());
                    line.SetAmtSourceCr(imp.GetAmtSourceCr());
                    line.SetAmtSourceDr(imp.GetAmtSourceDr());
                    line.SetAmtAcct(imp.GetAmtAcctDr(), imp.GetAmtAcctCr());    //	only if not 0
                    line.SetDateAcct(imp.GetDateAcct());
                    //
                    line.SetC_UOM_ID(imp.GetC_UOM_ID());
                    line.SetQty(imp.GetQty());
                    //
                    if (line.Save())
                    {
                        imp.SetGL_JournalBatch_ID(batch.GetGL_JournalBatch_ID());
                        imp.SetGL_Journal_ID(journal.GetGL_Journal_ID());
                        imp.SetGL_JournalLine_ID(line.GetGL_JournalLine_ID());
                        imp.SetI_IsImported(X_I_GLJournal.I_ISIMPORTED_Yes);
                        imp.SetProcessed(true);
                        if (imp.Save())
                        {
                            noInsertLine++;
                        }
                    }
                }       //	while records
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "", e);
            }
            //	clean up

            //	Set Error to indicator to not imported
            sql = new StringBuilder("UPDATE I_GLJournal "
                                    + "SET I_IsImported='N', Updated=SysDate "
                                    + "WHERE I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            AddLog(0, null, Utility.Util.GetValueOfDecimal(no), "@Errors@");
            //
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsert), "@GL_JournalBatch_ID@: @Inserted@");
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsertJournal), "@GL_Journal_ID@: @Inserted@");
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsertLine), "@GL_JournalLine_ID@: @Inserted@");
            return("");
        }       //	doIt