protected override string DoIt()
        {
            MCash cashheader = new MCash(GetCtx(), GetRecord_ID(), Get_Trx());

            sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cashheader.GetC_CashBook_ID();
            int C_Currencyheader_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));

            sql = "select * from C_Cashline WHERE C_Cash_ID=" + GetRecord_ID();
            DataSet dscashline = DB.ExecuteDataset(sql, null, Get_Trx());

            if (dscashline != null)
            {
                if (dscashline.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < dscashline.Tables[0].Rows.Count; i++)
                    {
                        cashline = new MCashLine(GetCtx(), Util.GetValueOfInt(dscashline.Tables[0].Rows[i]["C_CashLine_ID"]), Get_Trx());
                        if (cashline.GetCashType().ToString() == "A" || cashline.GetCashType().ToString() == "F")
                        {
                            sql = "Select * from C_Cash where C_CashBook_Id=" + cashline.GetC_CashBook_ID() + " and docstatus='DR' and  DateAcct=" + GlobalVariable.TO_DATE(DateTime.Now, true);
                            DataSet dscashbook = DB.ExecuteDataset(sql, null, Get_Trx());
                            if (dscashbook != null)
                            {
                                if (dscashbook.Tables[0].Rows.Count > 0)
                                {
                                    int j;
                                    for (j = 0; j < dscashbook.Tables[0].Rows.Count; j++)
                                    {
                                        cash = new MCash(GetCtx(), Util.GetValueOfInt(dscashbook.Tables[0].Rows[j]["C_Cash_ID"]), Get_Trx());
                                        if (!_cashIds.Contains(cash.GetC_Cash_ID()))
                                        {
                                            _cashIds.Add(cash.GetC_Cash_ID());
                                        }
                                        //ViennaAdvantage.Model.MCashLine cashline1 = new ViennaAdvantage.Model.MCashLine(GetCtx(), 0, Get_Trx());
                                        MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                        cashline1.SetC_Cash_ID(cash.GetC_Cash_ID());
                                        cashline1.SetAD_Client_ID(cash.GetAD_Client_ID());
                                        cashline1.SetAD_Org_ID(cash.GetAD_Org_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetCashType("F");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetCashType("A");
                                        }
                                        // Added by Bharat as discussed with Ravikant on 22 March 2017
                                        if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                        {
                                            cashline1.SetC_ConversionType_ID(cashline.GetC_ConversionType_ID());
                                        }
                                        cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                        cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                        sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash.GetC_CashBook_ID();
                                        Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (Currency_ID == C_Currencyheader_ID)
                                        {
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            //cashline1.SetC_Currency_ID(Currency_ID);
                                            // Change by Bharat as discussed with Ravikant on 22 March 2017
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                            {
                                                //_Curencyrate = MConversionRate.GetRate(C_Currencyheader_ID, Currency_ID, cash.GetDateAcct(), cashline.GetC_ConversionType_ID(),
                                                //    cash.GetAD_Client_ID(), cash.GetAD_Org_ID());

                                                convertedamount = Decimal.Negate(Util.GetValueOfDecimal(cashline.GetConvertedAmt()));

                                                // if converted amount not found then get amount based on currency conversion avaliable
                                                if (cashline.GetAmount() != 0 && convertedamount == 0)
                                                {
                                                    convertedamount = MConversionRate.Convert(GetCtx(), Decimal.Negate(cashline.GetAmount()), Currency_ID, C_Currencyheader_ID,
                                                                                              cash.GetDateAcct(), cashline.GetC_ConversionType_ID(), cash.GetAD_Client_ID(), cash.GetAD_Org_ID());
                                                    cashline.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(convertedamount)));
                                                }

                                                if (cashline.GetAmount() != 0 && convertedamount == 0)
                                                {
                                                    return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                                }
                                                else if (cashline.GetAmount() == 0)
                                                {
                                                    return("Amount Should be greater than zero");
                                                }
                                                cashline1.SetAmount(convertedamount);
                                                cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                            }
                                            else
                                            {
                                                sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                                _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                                if (_Curencyrate == 0)
                                                {
                                                    return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                                }
                                                else
                                                {
                                                    convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                                }
                                                cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                                cashline1.SetAmount(convertedamount);
                                            }
                                        }

                                        cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("R");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("P");
                                        }
                                        cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                        if (!cashline1.Save())
                                        {
                                            Rollback();
                                            log.Severe("NotSaved");
                                            return(" NotSaved Cashline1 [ Header Found ]  ");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                        }
                                        if (!cashline.Save())
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cashline [ Header Found ]  ");
                                        }
                                        //change by Amit 1-june-2016 after discussion with ravikant

                                        //int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash.GetC_CashBook_ID(), null, Get_Trx()));
                                        //cash.SetBeginningBalance(BeginBal);
                                        //if (!cash.Save(Get_Trx()))
                                        //{
                                        //    Rollback();
                                        //    log.Severe("Not Saved");
                                        //    return " NotSaved Cash [ Header Found ]  ";

                                        //}

                                        //end

                                        break;
                                    }
                                }
                                else
                                {
                                    dscashbook.Dispose();

                                    MCash cash1 = new MCash(GetCtx(), 0, Get_Trx());
                                    cash1.SetAD_Client_ID(cashheader.GetAD_Client_ID());
                                    cash1.SetAD_Org_ID(cashheader.GetAD_Org_ID());
                                    cash1.SetC_DocType_ID(cashheader.GetC_DocType_ID());
                                    cash1.SetName(Util.GetValueOfString(System.DateTime.Today.ToShortDateString()));
                                    cash1.SetC_CashBook_ID(cashline.GetC_CashBook_ID());
                                    cash1.SetDateAcct(DateTime.Now);
                                    cash1.SetStatementDate(DateTime.Now);
                                    //change by Amit 1-june-2016 after discussion with ravikant
                                    int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select SUM(completedbalance + runningbalance) from c_cashbook where c_cashbook_id=" + cashline.GetC_CashBook_ID(), null, Get_Trx()));
                                    cash1.SetBeginningBalance(BeginBal);
                                    //end
                                    //Change by Bharat as discussed with Ravikant on 22 March 2017
                                    sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (cash1.Get_ColumnIndex("C_Currency_ID") > 0)
                                    {
                                        cash1.SetC_Currency_ID(Currency_ID);
                                    }
                                    //End
                                    if (!cash1.Save())
                                    {
                                        Rollback();

                                        VAdvantage.Model.ValueNamePair ppE = VLogger.RetrieveError();
                                        if (ppE != null)
                                        {
                                            return(ppE.GetName() + "<--->" + ppE.GetValue());
                                        }

                                        return("cash1 not saved [header not found->]");
                                    }
                                    // return cash1.GetC_Cash_ID() + "suc";
                                    if (!_cashIds.Contains(cash1.GetC_Cash_ID()))
                                    {
                                        _cashIds.Add(cash1.GetC_Cash_ID());
                                    }
                                    MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                    cashline1.SetC_Cash_ID(cash1.GetC_Cash_ID());
                                    cashline1.SetAD_Client_ID(cash1.GetAD_Client_ID());
                                    cashline1.SetAD_Org_ID(cash1.GetAD_Org_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetCashType("F");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetCashType("A");
                                    }
                                    if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                    {
                                        cashline1.SetC_ConversionType_ID(cashline.GetC_ConversionType_ID());
                                    }
                                    cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                    cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());

                                    //Change by Bharat as discussed with Ravikant on 22 March 2017
                                    //sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    //Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (Currency_ID == C_Currencyheader_ID)
                                    {
                                        cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                    }
                                    else
                                    {
                                        //Change by Bharat as discussed with Ravikant on 22 March 2017
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        if (cashline1.Get_ColumnIndex("C_ConversionType_ID") > 0)
                                        {
                                            //_Curencyrate = MConversionRate.GetRate(C_Currencyheader_ID, Currency_ID, cashheader.GetDateAcct(), cashline.GetC_ConversionType_ID(),
                                            //    cashheader.GetAD_Client_ID(), cashheader.GetAD_Org_ID());
                                            convertedamount = Decimal.Negate(Util.GetValueOfDecimal(cashline.GetConvertedAmt()));

                                            // if converted amount not found then get amount based on currency conversion avaliable
                                            if (cashline.GetAmount() != 0 && convertedamount == 0)
                                            {
                                                convertedamount = MConversionRate.Convert(GetCtx(), Decimal.Negate(cashline.GetAmount()), Currency_ID, C_Currencyheader_ID,
                                                                                          cash1.GetDateAcct(), cashline.GetC_ConversionType_ID(), cash1.GetAD_Client_ID(), cash1.GetAD_Org_ID());
                                                cashline.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(convertedamount)));
                                            }

                                            if (cashline.GetAmount() != 0 && convertedamount == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else if (cashline.GetAmount() == 0)
                                            {
                                                return("Amount Should be greater than zero");
                                            }
                                            cashline1.SetAmount(convertedamount);
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                            _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));

                                            if (_Curencyrate == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else
                                            {
                                                convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                            }
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                            cashline1.SetAmount(convertedamount);
                                        }
                                    }

                                    cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("R");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("P");
                                    }
                                    cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                    if (!cashline1.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline1 [ Header not Found ]  ");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                    }
                                    if (!cashline.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline [ Header not Found ]  ");
                                    }
                                    //change by Amit 1-june-2016 after discussion with ravikant

                                    //int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash1.GetC_CashBook_ID(), null, Get_Trx()));
                                    //cash1.SetBeginningBalance(BeginBal);
                                    //if (!cash1.Save())
                                    //{
                                    //    Rollback();
                                    //    log.Severe("NotSaved");
                                    //    return " NotSaved Cash1 [ Header not Found(bb) ]  ";
                                    //}

                                    //end
                                }
                            }
                            else
                            {
                                //dscashbook.Dispose();
                            }
                        }
                        else
                        {
                            cashtype++;
                        }
                    }
                    // Discussed with Ravikant it is re updating the Header so commented on 23-March-2017 by Bharat
                    //decimal OpenBal = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT completedbalance FROM  C_CashBook WHERE c_cashbook_id=" + cashheader.GetC_CashBook_ID() + "", null, Get_Trx()));
                    //cashheader.SetBeginningBalance(OpenBal);
                    //if (!cashheader.Save())
                    //{
                    //    Rollback();
                    //    log.Severe("Not Saved");
                    //}
                }
                else
                {
                    dscashline.Dispose();
                    cashheader.SetGenerateCashBookTransfer("Y");
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("NotSaved");
                    }
                    return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
                }
                if (_cashIds.Count > 0)
                {
                    for (int k = 0; k < _cashIds.Count; k++)
                    {
                        cash = new MCash(GetCtx(), _cashIds[k], Get_Trx());
                        cash.SetDocStatus(cash.CompleteIt());
                        if (!cash.Save())
                        {
                            Rollback();
                            log.Severe("NotSaved");
                        }
                    }
                }
            }

            cashheader.SetGenerateCashBookTransfer("Y");
            if (!cashheader.Save())
            {
                log.Severe("NotSaved");
            }
            if (cashtype == i)
            {
                return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
            }
            return("Completed");
        }
        }       //	closeIt

        /// <summary>
        /// Reverse Correction.As if nothing happened - same date
        /// </summary>
        /// <returns>true if success </returns>
        public Boolean ReverseCorrectIt()
        {
            log.Info("reverseCorrectIt - " + ToString());
            MJournal[] journals = GetJournals(true);
            //	check prerequisites
            for (int i = 0; i < journals.Length; i++)
            {
                MJournal journal = journals[i];
                if (!journal.IsActive())
                {
                    continue;
                }
                //	All need to be closed/Completed
                if (DOCSTATUS_Completed.Equals(journal.GetDocStatus()))
                {
                    ;
                }
                else
                {
                    m_processMsg = "All Journals need to be Compleded: " + journal.GetSummary();
                    return(false);
                }
            }

            //	Reverse it
            MJournalBatch reverse = new MJournalBatch(this);

            reverse.SetDateDoc(GetDateDoc());
            reverse.SetC_Period_ID(GetC_Period_ID());
            reverse.SetDateAcct(GetDateAcct());
            reverse.SetC_Year_ID(GetC_Year_ID());
            //	Reverse indicator

            if (reverse.Get_ColumnIndex("ReversalDoc_ID") > 0 && reverse.Get_ColumnIndex("IsReversal") > 0)
            {
                // set Reversal property for identifying, record is reversal or not during saving or for other actions
                reverse.SetIsReversal(true);
                // Set Orignal Document Reference
                reverse.SetReversalDoc_ID(GetGL_JournalBatch_ID());
            }

            // for reversal document set Temp Document No to empty
            if (reverse.Get_ColumnIndex("TempDocumentNo") > 0)
            {
                reverse.SetTempDocumentNo("");
            }

            String description = reverse.GetDescription();

            if (description == null)
            {
                description = "** " + GetDocumentNo() + " **";
            }
            else
            {
                description += " ** " + GetDocumentNo() + " **";
                reverse.SetDescription(description);
            }
            if (!reverse.Save())
            {
                ValueNamePair pp = VLogger.RetrieveError();
                if (pp != null && !String.IsNullOrEmpty(pp.GetName()))
                {
                    m_processMsg = pp.GetName() + " - " + "Could not reverse " + this;
                }
                else
                {
                    m_processMsg = "Could not reverse " + this;
                }
                return(false);
            }
            //

            //	Reverse Journals
            for (int i = 0; i < journals.Length; i++)
            {
                MJournal journal = journals[i];
                if (!journal.IsActive())
                {
                    continue;
                }
                if (journal.ReverseCorrectIt(reverse.GetGL_JournalBatch_ID()) == null)
                {
                    m_processMsg = "Could not reverse " + journal;
                    return(false);
                }
                journal.Save();
            }
            return(true);
        }       //	reverseCorrectionIt
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override bool BeforeSave(bool newRecord)
        {
            if (Is_ValueChanged("DueAmt"))
            {
                log.Fine("beforeSave");
                SetIsValid(false);
            }
            oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt"));

            if (Env.IsModuleInstalled("VA009_"))
            {
                // get invoice currency for rounding
                MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID());
                SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision()));
                SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision()));

                // when invoice schedule have payment reference then need to check payment mode on payment window & update here
                if (GetC_Payment_ID() > 0)
                {
                    #region for payment
                    MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx());
                    SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID());

                    // get payment method detail -- update to here
                    DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE VA009_PaymentMethod_ID = " + payment.GetVA009_PaymentMethod_ID(), null, Get_Trx());
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    #endregion
                }
                else if (GetC_CashLine_ID() > 0)
                {
                    #region For Cash
                    // when invoice schedule have cashline reference then need to check
                    // payment mode of "Cash" type having currency is null on "Payment Method" window & update here
                    DataSet dsPaymentMethod = (DB.ExecuteDataset(@"SELECT VA009_PaymentMethod_ID, VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger 
                                       FROM VA009_PaymentMethod WHERE IsActive = 'Y' 
                                       AND AD_Client_ID = " + GetAD_Client_ID() + @" AND VA009_PaymentBaseType = 'B' AND NVL(C_Currency_ID , 0) = 0", null, Get_Trx()));
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        SetVA009_PaymentMethod_ID(Util.GetValueOfInt(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMethod_ID"]));
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    else
                    {
                        #region when we not found record of "Cash" then we will create a new rcord on Payment Method for Cash
                        string sql     = @"SELECT AD_TABLE_ID  FROM AD_TABLE WHERE tablename LIKE 'VA009_PaymentMethod' AND IsActive = 'Y'";
                        int    tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                        MTable tbl     = new MTable(GetCtx(), tableId, Get_Trx());
                        PO     po      = tbl.GetPO(GetCtx(), 0, Get_Trx());
                        po.SetAD_Client_ID(GetAD_Client_ID());
                        po.SetAD_Org_ID(0); // Recod will be created in (*) Organization
                        po.Set_Value("Value", "By Cash");
                        po.Set_Value("VA009_Name", "By Cash");
                        po.Set_Value("IsActive", true);
                        po.Set_Value("VA009_PaymentBaseType", "B");
                        po.Set_Value("VA009_PaymentRule", "M");
                        po.Set_Value("VA009_PaymentMode", "C");
                        po.Set_Value("VA009_PaymentType", "S");
                        po.Set_Value("VA009_PaymentTrigger", "S");
                        po.Set_Value("C_Currency_ID", null);
                        po.Set_Value("VA009_InitiatePay", false);
                        if (!po.Save(Get_Trx()))
                        {
                            ValueNamePair pp = VLogger.RetrieveError();
                            log.Info("Error Occured when try to save record on Payment Method for Cash. Error Type : " + pp.GetValue());
                        }
                        else
                        {
                            SetVA009_PaymentMethod_ID(Util.GetValueOfInt(po.Get_Value("VA009_PaymentMethod_ID")));
                            SetVA009_PaymentMode("C");
                            SetVA009_PaymentType("S");
                            SetVA009_PaymentTrigger("S");
                        }
                        #endregion
                    }
                    #endregion
                }
            }
            // to set processing false because in case of new schedule processing is set to be false
            if (newRecord)
            {
                SetProcessing(false);
            }
            return(true);
        }
Beispiel #4
0
        }       //	toString

        /// <summary>
        /// Execute Run.
        /// </summary>
        /// <returns>clear text info</returns>
        public String ExecuteRun()
        {
            DateTime?dateDoc = GetDateNextRun();

            if (!CalculateRuns())
            {
                throw new Exception("No Runs Left");
            }
            //	log
            MRecurringRun run = new MRecurringRun(GetCtx(), this);
            String        msg = "@Created@ ";

            //Checked if the Next Date Run is less then the date pressent Arpit on 15th Dec,2016
            if (GetDateNextRun() == DateTime.Now.Date || GetDateNextRun() == null)
            {
                //	Copy
                if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Order))
                {
                    MOrder from  = new MOrder(GetCtx(), 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 (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Invoice))
                {
                    MInvoice from    = new MInvoice(GetCtx(), 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());
                    //Set Invoice Refrence and Description from Orignal to Recurring
                    invoice.Set_Value("InvoiceReference", from.GetDocumentNo() + "_" + (GetRunsMax() - GetRunsRemaining() + 1));
                    invoice.AddDescription(Msg.GetMsg(from.GetCtx(), "RecurringDocument") + from.GetDocumentNo());
                    if (!invoice.Save(Get_TrxName()))
                    {
                        ValueNamePair pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            from.SetProcessMsg(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice") + pp.GetName());
                        }
                        else
                        {
                            from.SetProcessMsg(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice"));
                        }
                        throw new Exception(Msg.GetMsg(from.GetCtx(), "CouldNotCreateInvoice") + (pp != null ? pp.GetName() : ""));
                    }
                    msg += invoice.GetDocumentNo();
                }
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Project))
                {
                    MProject project = MProject.CopyFrom(GetCtx(), GetC_Project_ID(), dateDoc, Get_TrxName());
                    run.SetC_Project_ID(project.GetC_Project_ID());
                    msg += project.GetValue();
                }
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournalBatch)) //Changes to GL Journal Batch by Arpit
                {
                    MJournalBatch journal = MJournalBatch.CopyFrom(GetCtx(), GetGL_JournalBatch_ID(), dateDoc, Get_TrxName());
                    run.SetGL_JournalBatch_ID(journal.GetGL_JournalBatch_ID());
                    msg += journal.GetDocumentNo();
                }
                //Added by Arpit on 14th, Dec,2016
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_GLJournal))
                {
                    MJournal Journal = MJournal.CopyFrom(GetCtx(), GetGL_Journal_ID(), dateDoc, Get_TrxName());
                    run.SetGL_Journal_ID(Journal.GetGL_Journal_ID());
                    msg += Journal.GetDocumentNo();
                }

                //End here
                else if (GetRecurringType().Equals(MRecurring.RECURRINGTYPE_Payment))
                {
                    MPayment from    = new MPayment(GetCtx(), 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@ = " + GetRecurringType());
                }
                run.Save(Get_TrxName());

                //
                SetDateLastRun(run.GetUpdated());
                SetRunsRemaining(GetRunsRemaining() - 1);
                SetDateNextRun();
                Save(Get_TrxName());
                return(msg);
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "RecurringNotCompleted") + String.Format("{0:dd/M/yyyy}", Convert.ToDateTime(GetDateNextRun())));
            }
        }       //	execureRun
        /// <summary>
        /// This function will create child record of Cost Queue, which will contain transaction affects
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="AD_Client_ID">Client ID</param>
        /// <param name="AD_Org_ID">Organization ID</param>
        /// <param name="M_CostQueue_ID">Cost Queue ID</param>
        /// <param name="cd">Cost Detail Reference</param>
        /// <param name="qty">qty</param>
        /// <returns>true, when success</returns>
        public static bool CreateCostQueueTransaction(Ctx ctx, int AD_Client_ID, int AD_Org_ID, int M_CostQueue_ID, MCostDetail cd, decimal qty)
        {
            try
            {
                MCostQueueTransaction ced = new MCostQueueTransaction(ctx, 0, cd.Get_Trx());
                ced.SetAD_Client_ID(AD_Client_ID);
                ced.SetAD_Org_ID(AD_Org_ID);
                ced.SetM_CostQueue_ID(M_CostQueue_ID);
                ced.SetM_Product_ID(cd.GetM_Product_ID());
                ced.SetM_AttributeSetInstance_ID(cd.GetM_AttributeSetInstance_ID());
                ced.SetM_Warehouse_ID(cd.GetM_Warehouse_ID());

                // date and qty
                ced.SetMovementQty(qty);
                ced.SetMovementDate(DateTime.Now);

                //Refrences
                ced.SetM_InOutLine_ID(cd.GetM_InOutLine_ID());
                if (ced.GetM_InOutLine_ID() > 0)
                {
                    DataSet ds = DB.ExecuteDataset(@"SELECT M_InOut.IsSOTrx, M_InOut.IsReturnTrx FROM M_InOutLine
                                    INNER JOIN M_InOut ON M_InOutLine.M_InOut_ID = M_InOut.M_InOut_ID 
                                    WHERE M_InOutLine.M_InOutLine_ID = " + ced.GetM_InOutLine_ID(), null, cd.Get_Trx());
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        ced.SetIsSOTrx(Util.GetValueOfString(ds.Tables[0].Rows[0]["IsSOTrx"]).Equals("N") ? false : true);
                        ced.SetIsReturnTrx(Util.GetValueOfString(ds.Tables[0].Rows[0]["IsReturnTrx"]).Equals("N") ? false : true);
                    }
                }
                ced.SetM_InventoryLine_ID(cd.GetM_InventoryLine_ID());
                if (ced.GetM_InventoryLine_ID() > 0)
                {
                    bool isInternalUse = Util.GetValueOfString(DB.ExecuteScalar(@"SELECT M_Inventory.IsInternalUse  FROM M_InventoryLine
                                    INNER JOIN M_Inventory ON M_InventoryLine.M_Inventory_ID = M_Inventory.M_Inventory_ID 
                                    WHERE M_InventoryLine.M_InventoryLine_ID = " + ced.GetM_InventoryLine_ID(), null, cd.Get_Trx())).Equals("N") ? false : true;
                    ced.SetIsInternalUse(isInternalUse);
                }
                ced.SetM_MovementLine_ID(cd.GetM_MovementLine_ID());
                ced.SetC_ProjectIssue_ID(cd.GetC_ProjectIssue_ID());
                //ced.SetA_Asset_ID(cd.GetA_Asset_ID());
                ced.SetM_ProductionLine_ID(cd.GetM_ProductionLine_ID());
                if (Env.IsModuleInstalled("VAFAM_") && ced.Get_ColumnIndex("VAFAM_AssetDisposal_ID") > -1)
                {
                    ced.Set_Value("VAFAM_AssetDisposal_ID", cd.Get_Value("VAFAM_AssetDisposal_ID"));
                }
                if (Env.IsModuleInstalled("VAMFG_"))
                {
                    if (ced.Get_ColumnIndex("VAMFG_M_WrkOdrRscTxnLine_ID") > -1)
                    {
                        ced.Set_Value("VAMFG_M_WrkOdrRscTxnLine_ID", cd.GetVAMFG_M_WrkOdrRscTxnLine_ID());
                    }
                    if (ced.Get_ColumnIndex("VAMFG_M_WrkOdrTrnsctionLine_ID") > -1)
                    {
                        ced.Set_Value("VAMFG_M_WrkOdrTrnsctionLine_ID", cd.GetVAMFG_M_WrkOdrTrnsctionLine_ID());
                    }
                }
                if (!ced.Save())
                {
                    ValueNamePair pp    = VLogger.RetrieveError();
                    string        error = "";
                    if (pp != null)
                    {
                        error = pp.GetValue();
                        if (String.IsNullOrEmpty(error))
                        {
                            error = pp.GetValue();
                        }
                    }
                    _log.Info("Costing Engine : Error Occured during saving a record on Cost Queue Transaction -> " + error);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _log.Info("Costing Engine : Exception Occured during saving a record on Cost Queue Transaction " + ex.Message);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// After Save Logic
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        protected override bool AfterSave(bool newRecord, bool success)
        {
            // create default Account
            StringBuilder _sql = new StringBuilder();

            _sql.Append(DBFunctionCollection.CheckTableExistence(DB.GetSchema(), "FRPT_RevenueRecognition_Acct"));
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                _sql.Clear();
                _sql.Append("Select L.Value From Ad_Ref_List L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Revenue Recognition'");
                var relatedtoProduct = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));

                PO assetGroupAcct = null;
                _sql.Clear();
                _sql.Append("select C_AcctSchema_ID from C_AcctSchema where IsActive = 'Y' AND AD_CLIENT_ID=" + GetAD_Client_ID());
                DataSet ds3 = new DataSet();
                ds3 = DB.ExecuteDataset(_sql.ToString(), null);
                if (ds3 != null && ds3.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                    {
                        int _AcctSchema_ID = Util.GetValueOfInt(ds3.Tables[0].Rows[k]["C_AcctSchema_ID"]);
                        _sql.Clear();
                        _sql.Append("Select Frpt_Acctdefault_Id,C_Validcombination_Id,Frpt_Relatedto From Frpt_Acctschema_Default Where ISACTIVE='Y' AND AD_CLIENT_ID=" + GetAD_Client_ID() + "AND C_Acctschema_Id=" + _AcctSchema_ID);
                        DataSet ds = new DataSet();
                        ds = DB.ExecuteDataset(_sql.ToString(), null, Get_Trx());
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string _relatedTo = ds.Tables[0].Rows[i]["Frpt_Relatedto"].ToString();
                                if (!_relatedTo.Equals("") && _relatedTo.Equals(relatedtoProduct))
                                {
                                    _sql.Clear();
                                    _sql.Append(@"Select count(*) From C_RevenueRecognition Bp
                                                       Left Join FRPT_RevenueRecognition_Acct  ca On Bp.C_RevenueRecognition_ID=ca.C_RevenueRecognition_ID 
                                                        And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]
                                                + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + GetAD_Client_ID() +
                                                " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]) +
                                                " AND Bp.C_RevenueRecognition_ID = " + GetC_RevenueRecognition_ID());
                                    int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                    if (recordFound == 0)
                                    {
                                        assetGroupAcct = MTable.GetPO(GetCtx(), "FRPT_RevenueRecognition_Acct", 0, null);
                                        assetGroupAcct.Set_ValueNoCheck("AD_Org_ID", 0);
                                        assetGroupAcct.Set_ValueNoCheck("C_RevenueRecognition_ID", Util.GetValueOfInt(GetC_RevenueRecognition_ID()));
                                        assetGroupAcct.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                        assetGroupAcct.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                        assetGroupAcct.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                        if (!assetGroupAcct.Save())
                                        {
                                            ValueNamePair pp = VLogger.RetrieveError();
                                            log.Log(Level.SEVERE, "Could Not create FRPT_Asset_Groip_Acct. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(true);
        }
        /// <summary>
        /// After save logic for asset
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        protected override bool AfterSave(bool newRecord, bool success)
        {
            //Cost Code Commented - As not required on Asset Save
            //if (newRecord)
            //{
            //    UpdateAssetCost();
            //}

            // create default Account
            StringBuilder _sql = new StringBuilder("");

            // check table exist or not
            //_sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_Asset_Group_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            _sql.Append(DBFunctionCollection.CheckTableExistence(DB.GetSchema(), "FRPT_Asset_Group_Acct"));
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                PO  obj          = null;
                int assetId      = GetA_Asset_ID();
                int assetGroupId = GetA_Asset_Group_ID();
                // get related to value agaisnt asset = 75
                string sql = "SELECT L.VALUE FROM AD_REF_LIST L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where   r.name='FRPT_RelatedTo' and l.name='Asset'";
                string _RelatedToProduct = Convert.ToString(DB.ExecuteScalar(sql));

                _sql.Clear();
                _sql.Append("Select Count(*) From FRPT_Asset_Acct   where A_Asset_ID=" + assetId + " AND IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID());
                int value = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));
                if (value < 1)
                {
                    _sql.Clear();
                    _sql.Append(@"Select  PCA.c_acctschema_id, PCA.c_validcombination_id, PCA.frpt_acctdefault_id " +
                                " From FRPT_Asset_Group_Acct PCA " +
                                " inner join frpt_acctdefault ACC ON acc.frpt_acctdefault_id= PCA.frpt_acctdefault_id " +
                                " where PCA.A_Asset_Group_ID=" + assetGroupId +
                                " and acc.frpt_relatedto='" + _RelatedToProduct +
                                "' AND PCA.IsActive = 'Y' AND PCA.AD_Client_ID = " + GetAD_Client_ID());

                    DataSet ds = DB.ExecuteDataset(_sql.ToString());
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            obj = MTable.GetPO(GetCtx(), "FRPT_Asset_Acct", 0, null);
                            obj.Set_ValueNoCheck("AD_Org_ID", 0);
                            obj.Set_ValueNoCheck("A_Asset_ID", assetId);
                            obj.Set_ValueNoCheck("C_AcctSchema_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_AcctSchema_ID"]));
                            obj.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_ValidCombination_ID"]));
                            obj.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                            if (!obj.Save())
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Log(Level.SEVERE, "Could Not create FRPT_Asset_Acct. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName());
                            }
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Get Data Direct from Table.
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="saveInCache">save in cache for r/w</param>
        /// <param name="cacheLocal">cache locally for r/o</param>
        /// <returns></returns>

        public override NamePair GetDirect(Object key, bool saveInCache, bool cacheLocal)
        {
            //	Nothing to query
            if (key == null || _vInfo.queryDirect == null || _vInfo.queryDirect.Length == 0)
            {
                return(null);
            }
            if (key.Equals(_directNullKey))
            {
                return(null);
            }
            //
            NamePair directValue = null;

            if (_lookupDirect != null)          //	Lookup cache
            {
                object o = null;
                _lookupDirect.TryGetValue(key, out o);
                if (o != null && o is NamePair)
                {
                    return((NamePair)o);
                }
            }
            log.Finer(_vInfo.keyColumn + ": " + key
                      + ", SaveInCache=" + saveInCache + ",Local=" + cacheLocal);
            bool isNumber = _vInfo.keyColumn.EndsWith("_ID");

            System.Data.IDataReader dr = null;
            try
            {
                //	SELECT Key, Value, Name FROM ...
                System.Data.SqlClient.SqlParameter[] param = new System.Data.SqlClient.SqlParameter[1];
                if (isNumber)
                {
                    param[0] = new System.Data.SqlClient.SqlParameter("@key", int.Parse(key.ToString()));
                }
                else
                {
                    param[0] = new System.Data.SqlClient.SqlParameter("@key", key.ToString());
                }

                dr = SqlExec.ExecuteQuery.ExecuteReader(_vInfo.queryDirect, param);
                if (dr.Read())
                {
                    String name = dr[2].ToString();
                    if (isNumber)
                    {
                        int keyValue = Utility.Util.GetValueOfInt(dr[0]);
                        //object keyValue = dr[0];
                        KeyNamePair p = new KeyNamePair(keyValue, name);
                        if (saveInCache)                //	save if
                        {
                            _lookup.Add(keyValue, p);
                        }
                        directValue = p;
                    }
                    else
                    {
                        String        value = dr.GetString(1);
                        ValueNamePair p     = new ValueNamePair(value, name);
                        if (saveInCache)                //	save if
                        {
                            _lookup.Add(value, p);
                        }
                        directValue = p;
                    }
                    if (dr.Read())
                    {
                        log.Log(Level.SEVERE, _vInfo.keyColumn + ": Not unique (first returned) for "
                                + key + " SQL=" + _vInfo.queryDirect);
                    }
                }
                else
                {
                    _directNullKey = key;
                    directValue    = null;
                }
                if (VLogMgt.IsLevelFinest())
                {
                    log.Finest(_vInfo.keyColumn + ": " + directValue + " - " + _vInfo);
                }
                dr.Close();
                dr = null;
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, _vInfo.keyColumn + ": SQL=" + _vInfo.queryDirect + "; Key=" + key, e);
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
                directValue = null;
            }


            //	Cache Local if not added to R/W cache
            if (cacheLocal && !saveInCache && directValue != null)
            {
                if (_lookupDirect == null)
                {
                    _lookupDirect = new Dictionary <object, object>();
                }
                _lookupDirect.Add(key, directValue);
            }
            _hasInactive = true;
            return(directValue);
        }
        /// <summary>
        /// This function is used to create Recognition plan and run
        /// </summary>
        /// <param name="C_InvoiceLine_ID">invoice line</param>
        /// <param name="C_RevenueRecognition_ID">Revenue Recognition</param>
        /// <param name="Invoice">Invoice</param>
        /// <returns>true, when success</returns>
        public static bool CreateRevenueRecognitionPlan(int C_InvoiceLine_ID, int C_RevenueRecognition_ID, MInvoice Invoice)
        {
            try
            {
                MRevenueRecognitionRun revenueRecognitionRun = null;
                DateTime?           RecognizationDate        = null;
                int                 NoofMonths             = 0;
                MRevenueRecognition revenueRecognition     = new MRevenueRecognition(Invoice.GetCtx(), C_RevenueRecognition_ID, Invoice.Get_Trx());
                int                 defaultAccSchemaOrg_ID = GetDefaultActSchema(Invoice.GetCtx(), Invoice.GetAD_Client_ID(), Invoice.GetAD_Org_ID());
                int                 ToCurrency             = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Currency_ID FROM C_AcctSchema WHERE C_AcctSchema_ID=" + defaultAccSchemaOrg_ID));

                MInvoiceLine invoiceLine = new MInvoiceLine(Invoice.GetCtx(), C_InvoiceLine_ID, Invoice.Get_Trx());

                //if recoganization date is null recognition plan and run cant be generated
                if (invoiceLine.Get_Value("RevenueStartDate") == null)
                {
                    _log.Log(Level.SEVERE, "DateIsInvlidOrNull");
                    return(false);
                }
                RecognizationDate = Util.GetValueOfDateTime(invoiceLine.Get_Value("RevenueStartDate"));

                // precision to be handle based on std precision defined on acct schema
                string sql          = "SELECT C.StdPrecision FROM C_AcctSchema a INNER JOIN C_Currency c ON c.C_Currency_ID= a.C_Currency_ID WHERE a.C_AcctSchema_ID=" + defaultAccSchemaOrg_ID;
                int    stdPrecision = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));


                if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Month) && RecognizationDate.Value.Day != 1 && revenueRecognition.GetNoMonths() > 0)
                {
                    //if startdate is in between day of month
                    NoofMonths = revenueRecognition.GetNoMonths() + 1;
                }
                else
                {
                    //if start date is the first day of the month
                    NoofMonths = revenueRecognition.GetNoMonths();
                }
                MRevenueRecognitionPlan revenueRecognitionPlan = new MRevenueRecognitionPlan(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                revenueRecognitionPlan.SetRecognitionPlan(invoiceLine, Invoice, C_RevenueRecognition_ID, ToCurrency);
                revenueRecognitionPlan.SetC_AcctSchema_ID(defaultAccSchemaOrg_ID);
                revenueRecognitionPlan.SetRecognizedAmt(0);
                if (!revenueRecognitionPlan.Save())
                {
                    ValueNamePair pp    = VLogger.RetrieveError();
                    string        error = pp != null?pp.GetValue() : "";

                    if (pp != null && string.IsNullOrEmpty(error))
                    {
                        error = pp.GetName();
                    }
                    if (!string.IsNullOrEmpty(error))
                    {
                        _log.Log(Level.SEVERE, error);
                        return(false);
                    }
                }
                else
                {
                    if (!revenueRecognition.IsTimeBased())
                    {
                    }
                    else
                    {
                        if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Month))
                        {
                            decimal totaldays = Util.GetValueOfDecimal((RecognizationDate.Value.AddMonths(revenueRecognition.GetNoMonths()) - RecognizationDate.Value.Date).TotalDays);

                            decimal  perdayAmt     = Math.Round(revenueRecognitionPlan.GetTotalAmt() / (totaldays > 0?totaldays:1), 12);
                            decimal  recognizedAmt = 0;
                            DateTime?lastdate      = null;
                            int      days          = 0;
                            for (int i = 0; i < NoofMonths; i++)
                            {
                                if (i == 0)
                                {
                                    if (RecognizationDate.Value.Month == 12)
                                    {
                                        //last date of the month
                                        lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month, 1).AddMonths(1).AddDays(-1);
                                    }
                                    else
                                    {
                                        //last date of the month
                                        lastdate = new DateTime(RecognizationDate.Value.Year, RecognizationDate.Value.Month + 1, 1).AddDays(-1);
                                    }
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - RecognizationDate.Value.Date).TotalDays);
                                    days += 1;
                                }
                                else if (i == (revenueRecognition.GetNoMonths()))
                                {
                                    //last date of the month would the day before  the recoganizationdate
                                    lastdate = RecognizationDate.Value.AddMonths(i).AddDays(-1);
                                    DateTime startDate = new DateTime(lastdate.Value.Year, lastdate.Value.Month, 1);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - startDate.Date).TotalDays);
                                    days += 1;
                                }
                                else
                                {
                                    DateTime startDate = lastdate.Value.AddDays(1);
                                    days     = DateTime.DaysInMonth(startDate.Year, startDate.Month);
                                    lastdate = startDate.AddDays(days - 1);
                                }
                                recognizedAmt         = Math.Round(days * perdayAmt, stdPrecision);
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(lastdate);
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                                recognizedAmt = 0;
                            }
                        }
                        else if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Day))
                        {
                            Decimal recognizedAmt = Math.Round(revenueRecognitionPlan.GetTotalAmt() / revenueRecognition.GetNoMonths(), stdPrecision);
                            int     days          = 0;
                            for (int i = 0; i < revenueRecognition.GetNoMonths(); i++)
                            {
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(RecognizationDate.Value.AddDays(days));
                                days += 1;
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                            }
                        }
                        else if (revenueRecognition.GetRecognitionFrequency().Equals(RECOGNITIONFREQUENCY_Year))
                        {
                            DateTime?fstartDate  = null;
                            DateTime?fendDate    = null;
                            int      calendar_ID = 0;
                            DataSet  ds          = new DataSet();

                            calendar_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Calendar_ID FROM AD_OrgInfo WHERE ad_org_id = " + Invoice.GetAD_Org_ID()));
                            if (calendar_ID == 0)
                            {
                                calendar_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT C_Calendar_ID FROM AD_ClientInfo WHERE ad_client_id = " + Invoice.GetAD_Client_ID()));
                            }
                            sql = "SELECT startdate , enddate FROM c_period WHERE " +
                                  "c_year_id = (SELECT c_year.c_year_id FROM c_year INNER JOIN C_period ON c_year.c_year_id = C_period.c_year_id " +
                                  "WHERE  c_year.c_calendar_id =" + calendar_ID + " AND " + GlobalVariable.TO_DATE(RecognizationDate, true) + " BETWEEN C_period.startdate AND C_period.enddate) AND periodno IN (1, 12)";
                            ds = DB.ExecuteDataset(sql);
                            if (ds != null && ds.Tables[0].Rows.Count > 0)
                            {
                                fstartDate = Convert.ToDateTime(ds.Tables[0].Rows[0]["startdate"]);
                                fendDate   = Convert.ToDateTime(ds.Tables[0].Rows[1]["enddate"]);
                            }
                            if (fstartDate != RecognizationDate)
                            {
                                //RecognizationDate  is not same as financial year's start date
                                NoofMonths += 1;
                            }
                            decimal totaldays = Util.GetValueOfDecimal((RecognizationDate.Value.AddYears(revenueRecognition.GetNoMonths()) - RecognizationDate.Value.Date).TotalDays);

                            decimal  perdayAmt     = Math.Round(revenueRecognitionPlan.GetTotalAmt() / (totaldays > 0?totaldays:1), 12);
                            decimal  recognizedAmt = 0;
                            DateTime?lastdate      = null;
                            int      days          = 0;
                            for (int i = 0; i < NoofMonths; i++)
                            {
                                if (i == 0)
                                {
                                    //last date will always be financial year's end date
                                    lastdate = fendDate;
                                    days     = Util.GetValueOfInt((lastdate.Value.Date - RecognizationDate.Value.Date).TotalDays);
                                    days    += 1;
                                }
                                else if (i == revenueRecognition.GetNoMonths())
                                {
                                    //last date of the year would the day before the recoganizationdate
                                    lastdate = RecognizationDate.Value.AddYears(i).AddDays(-1);
                                    DateTime startDate = fstartDate.Value.AddYears(i);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - startDate.Date).TotalDays);
                                    days += 1;
                                }
                                else
                                {
                                    lastdate = fendDate.Value.AddYears(i);
                                    DateTime _startDate = fstartDate.Value.AddYears(i);
                                    days  = Util.GetValueOfInt((lastdate.Value.Date - _startDate.Date).TotalDays);
                                    days += 1;
                                }
                                recognizedAmt         = Math.Round(days * perdayAmt, stdPrecision);
                                revenueRecognitionRun = new MRevenueRecognitionRun(Invoice.GetCtx(), 0, Invoice.Get_Trx());
                                revenueRecognitionRun.SetRecognitionRun(revenueRecognitionPlan);
                                revenueRecognitionRun.SetRecognizedAmt(recognizedAmt);
                                revenueRecognitionRun.SetRecognitionDate(lastdate);
                                if (!revenueRecognitionRun.Save())
                                {
                                    ValueNamePair pp    = VLogger.RetrieveError();
                                    string        error = pp != null?pp.GetValue() : "";

                                    if (pp != null && string.IsNullOrEmpty(error))
                                    {
                                        error = pp.GetName();
                                    }
                                    if (!string.IsNullOrEmpty(error))
                                    {
                                        _log.Log(Level.SEVERE, error);
                                        return(false);
                                    }
                                }
                                recognizedAmt = 0;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Severe("Exception during creation of Recognition Plan and Run. " + ex.Message);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Load LookUp data by second thread
        /// </summary>
        private void Load()
        {
            long startTime = CommonFunctions.CurrentTimeMillis();// System.currentTimeMillis();

            string sql = _vInfo.query;

            //	not validated
            if (!_vInfo.isValidated)
            {
                string validation = Utility.Env.ParseContext(GetCtx(), GetWindowNo(), _vInfo.validationCode, false);
                if (validation.Length == 0 && _vInfo.validationCode.Length > 0)
                {
                    log.Fine(_vInfo.keyColumn + ": Loader NOT Validated: " + _vInfo.validationCode);
                    return;
                }
                else
                {
                    int  posFrom  = sql.LastIndexOf(" FROM ");
                    bool hasWhere = sql.IndexOf(" WHERE ", posFrom) != -1;
                    //
                    int posOrder = sql.LastIndexOf(" ORDER BY ");
                    if (posOrder != -1)
                    {
                        sql = sql.Substring(0, posOrder)
                              + (hasWhere ? " AND " : " WHERE ")
                              + validation
                              + sql.Substring(posOrder);
                    }
                    else
                    {
                        sql += (hasWhere ? " AND " : " WHERE ")

                               + validation;
                    }
                    if (VLogMgt.IsLevelFinest())
                    {
                        log.Fine(_vInfo.keyColumn + ": Validation=" + validation);
                    }
                }
            }
            //if (_loader.ThreadState == System.Threading.ThreadState.Suspended)
            //{
            //    return;
            //}
            if (VLogMgt.IsLevelFiner())
            {
                GetCtx().SetContext(Env.WINDOW_MLOOKUP, _vInfo.column_ID, _vInfo.keyColumn, sql);
            }
            if (VLogMgt.IsLevelFinest())
            {
                log.Fine(_vInfo.keyColumn + ": " + sql);
            }

            _lookup.Clear();

            bool isNumber = _vInfo.keyColumn.EndsWith("_ID");

            _hasInactive = false;
            int rows = 0;

            // KeyValuePair<string, Object> p = new KeyValuePair<string, Object>("", "");
            System.Data.IDataReader dr = null;
            try
            {
                dr         = SqlExec.ExecuteQuery.ExecuteReader(sql);
                _allLoaded = true;

                while (dr.Read())
                {
                    if (rows++ > MAX_ROWS)
                    {
                        log.Warning(_vInfo.keyColumn + ": Loader - Too many records");
                        _allLoaded = false;
                        break;
                    }

                    string name     = dr[2].ToString();
                    bool   isActive = dr[3].ToString().Equals("Y");
                    if (!isActive)
                    {
                        name         = INACTIVE_S + name + INACTIVE_E;
                        _hasInactive = true;
                    }

                    if (isNumber)
                    {
                        // object key = dr[0];
                        int         key = Utility.Util.GetValueOfInt(dr[0]);
                        KeyNamePair p   = new KeyNamePair(key, name);
                        _lookup[key] = p;
                    }

                    else
                    {
                        string        value = dr.GetString(1);
                        ValueNamePair p     = new ValueNamePair(value, name);
                        _lookup.Add(value, p);
                    }
                    //KeyValuePair<string, string> p = new KeyValuePair<string, string>();
                }
                dr.Close();
                dr = null;
            }
            catch (System.Exception e)
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
                log.Log(Level.SEVERE, _vInfo.keyColumn + ": Loader - " + sql, e);
                ////Common.////ErrorLog.FillErrorLog("Mlookup.Load()",sql,e.Message,VAdvantage.Framework.Message.MessageType.ERROR);
            }

            int size = _lookup.Count;

            log.Finer(_vInfo.keyColumn
                      + " (" + _vInfo.column_ID + "):"
                      //	+ " ID=" + m_info.AD_Column_ID + " " +
                      + " - Loader complete #" + size + " - all=" + _allLoaded
                      + " - ms=" + (CommonFunctions.CurrentTimeMillis() - startTime));
            //+ " (" + String.valueOf(System.currentTimeMillis() - startTime) + ")");
            //	if (m_allLoaded)

            MLookupCache.LoadEnd(_vInfo, _lookup, _allLoaded, _hasInactive);
        }
Beispiel #11
0
        protected override string DoIt()
        {
            MCash cashheader = new MCash(GetCtx(), GetRecord_ID(), Get_Trx());

            sql = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cashheader.GetC_CashBook_ID();
            int C_Currencyheader_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));

            sql = "select * from C_Cashline WHERE C_Cash_ID=" + GetRecord_ID();
            DataSet dscashline = DB.ExecuteDataset(sql, null, Get_Trx());

            if (dscashline != null)
            {
                if (dscashline.Tables[0].Rows.Count > 0)
                {
                    for (i = 0; i < dscashline.Tables[0].Rows.Count; i++)
                    {
                        cashline = new MCashLine(GetCtx(), Util.GetValueOfInt(dscashline.Tables[0].Rows[i]["C_CashLine_ID"]), Get_Trx());
                        if (cashline.GetCashType().ToString() == "A" || cashline.GetCashType().ToString() == "F")
                        {
                            sql = "Select * from C_Cash where C_CashBook_Id=" + cashline.GetC_CashBook_ID() + " and docstatus='DR' and  DateAcct=" + GlobalVariable.TO_DATE(DateTime.Now, true);
                            DataSet dscashbook = DB.ExecuteDataset(sql, null, Get_Trx());
                            if (dscashbook != null)
                            {
                                if (dscashbook.Tables[0].Rows.Count > 0)
                                {
                                    int j;
                                    for (j = 0; j < dscashbook.Tables[0].Rows.Count; j++)
                                    {
                                        cash = new MCash(GetCtx(), Util.GetValueOfInt(dscashbook.Tables[0].Rows[j]["C_Cash_ID"]), Get_Trx());
                                        if (!_cashIds.Contains(cash.GetC_Cash_ID()))
                                        {
                                            _cashIds.Add(cash.GetC_Cash_ID());
                                        }
                                        //ViennaAdvantage.Model.MCashLine cashline1 = new ViennaAdvantage.Model.MCashLine(GetCtx(), 0, Get_Trx());
                                        MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                        cashline1.SetC_Cash_ID(cash.GetC_Cash_ID());
                                        cashline1.SetAD_Client_ID(cash.GetAD_Client_ID());
                                        cashline1.SetAD_Org_ID(cash.GetAD_Org_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetCashType("F");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetCashType("A");
                                        }
                                        cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                        cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                        sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash.GetC_CashBook_ID();
                                        Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (Currency_ID == C_Currencyheader_ID)
                                        {
                                            cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                            cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                        }
                                        else
                                        {
                                            cashline1.SetC_Currency_ID(Currency_ID);
                                            sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                            _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                            if (_Curencyrate == 0)
                                            {
                                                return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                            }
                                            else
                                            {
                                                convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                            }
                                            cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                            cashline1.SetAmount(convertedamount);
                                        }

                                        cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                        if (cashline.GetCashType().ToString() == "A")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("R");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline1.SetVSS_PAYMENTTYPE("P");
                                        }
                                        cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                        if (!cashline1.Save())
                                        {
                                            Rollback();
                                            log.Severe("NotSaved");
                                            return(" NotSaved Cashline1 [ Header Found ]  ");
                                        }
                                        if (cashline.GetCashType().ToString() == "F")
                                        {
                                            cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                        }
                                        if (!cashline.Save())
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cashline [ Header Found ]  ");
                                        }

                                        int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash.GetC_CashBook_ID(), null, Get_Trx()));
                                        cash.SetBeginningBalance(BeginBal);
                                        if (!cash.Save(Get_Trx()))
                                        {
                                            Rollback();
                                            log.Severe("Not Saved");
                                            return(" NotSaved Cash [ Header Found ]  ");
                                        }

                                        break;
                                    }
                                }
                                else
                                {
                                    dscashbook.Dispose();

                                    MCash cash1 = new MCash(GetCtx(), 0, Get_Trx());
                                    cash1.SetAD_Client_ID(cashheader.GetAD_Client_ID());
                                    cash1.SetAD_Org_ID(cashheader.GetAD_Org_ID());
                                    cash1.SetC_DocType_ID(cashheader.GetC_DocType_ID());
                                    cash1.SetName(Util.GetValueOfString(System.DateTime.Today.ToShortDateString()));
                                    cash1.SetC_CashBook_ID(cashline.GetC_CashBook_ID());
                                    cash1.SetDateAcct(DateTime.Now);
                                    cash1.SetStatementDate(DateTime.Now);
                                    if (!cash1.Save())
                                    {
                                        Rollback();

                                        VAdvantage.Model.ValueNamePair ppE = VLogger.RetrieveError();
                                        if (ppE != null)
                                        {
                                            return(ppE.GetName() + "<--->" + ppE.GetValue());
                                        }

                                        return("cash1 not saved [header not found->]");
                                    }
                                    // return cash1.GetC_Cash_ID() + "suc";
                                    if (!_cashIds.Contains(cash1.GetC_Cash_ID()))
                                    {
                                        _cashIds.Add(cash1.GetC_Cash_ID());
                                    }
                                    MCashLine cashline1 = new MCashLine(GetCtx(), 0, Get_Trx());
                                    cashline1.SetC_Cash_ID(cash1.GetC_Cash_ID());
                                    cashline1.SetAD_Client_ID(cash1.GetAD_Client_ID());
                                    cashline1.SetAD_Org_ID(cash1.GetAD_Org_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetCashType("F");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetCashType("A");
                                    }

                                    cashline1.SetC_CashBook_ID(cashheader.GetC_CashBook_ID());
                                    cashline1.SetC_BPartner_ID(cashline.GetC_BPartner_ID());
                                    sql         = "select C_Currency_ID from  C_CashBook where c_Cashbook_id=" + cash1.GetC_CashBook_ID();
                                    Currency_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx()));
                                    if (Currency_ID == C_Currencyheader_ID)
                                    {
                                        cashline1.SetAmount(Decimal.Negate(cashline.GetAmount()));
                                        cashline1.SetC_Currency_ID(C_Currencyheader_ID);
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(Decimal.Negate(cashline.GetAmount())));
                                    }
                                    else
                                    {
                                        cashline1.SetC_Currency_ID(Currency_ID);
                                        sql          = "select multiplyrate from c_conversion_rate where isactive='Y' and c_currency_id=" + C_Currencyheader_ID + " and c_currency_to_id=" + Currency_ID;
                                        _Curencyrate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx()));
                                        if (_Curencyrate == 0)
                                        {
                                            return(Msg.GetMsg(GetCtx(), "NoCurrencyRateDefined"));
                                        }
                                        else
                                        {
                                            convertedamount = Decimal.Round(Decimal.Multiply(_Curencyrate, Decimal.Negate(cashline.GetAmount())), 2);
                                        }
                                        cashline1.SetConvertedAmt(Util.GetValueOfString(convertedamount));
                                        cashline1.SetAmount(convertedamount);
                                    }

                                    cashline1.SetC_Charge_ID(cashline.GetC_Charge_ID());
                                    if (cashline.GetCashType().ToString() == "A")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("R");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline1.SetVSS_PAYMENTTYPE("P");
                                    }
                                    cashline1.SetC_CashLine_ID_1(cashline.GetC_CashLine_ID());
                                    if (!cashline1.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline1 [ Header not Found ]  ");
                                    }
                                    if (cashline.GetCashType().ToString() == "F")
                                    {
                                        cashline.SetC_CashLine_ID_1(cashline1.GetC_CashLine_ID());
                                    }
                                    if (!cashline.Save(Get_Trx()))
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cashline [ Header not Found ]  ");
                                    }
                                    int BeginBal = Util.GetValueOfInt(DB.ExecuteScalar("select completedbalance from c_cashbook where c_cashbook_id=" + cash1.GetC_CashBook_ID(), null, Get_Trx()));
                                    cash1.SetBeginningBalance(BeginBal);
                                    if (!cash1.Save())
                                    {
                                        Rollback();
                                        log.Severe("NotSaved");
                                        return(" NotSaved Cash1 [ Header not Found(bb) ]  ");
                                    }
                                }
                            }
                            else
                            {
                                //dscashbook.Dispose();
                            }
                        }
                        else
                        {
                            cashtype++;
                        }
                    }
                    decimal OpenBal = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT completedbalance FROM  C_CashBook WHERE c_cashbook_id=" + cashheader.GetC_CashBook_ID() + "", null, Get_Trx()));
                    cashheader.SetBeginningBalance(OpenBal);
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("Not Saved");
                    }
                }
                else
                {
                    dscashline.Dispose();
                    cashheader.SetGenerateCashBookTransfer("Y");
                    if (!cashheader.Save())
                    {
                        Rollback();
                        log.Severe("NotSaved");
                    }
                    return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
                }
                if (_cashIds.Count > 0)
                {
                    for (int k = 0; k < _cashIds.Count; k++)
                    {
                        cash = new MCash(GetCtx(), _cashIds[k], Get_Trx());
                        cash.SetDocStatus(cash.CompleteIt());
                        if (!cash.Save())
                        {
                            Rollback();
                            log.Severe("NotSaved");
                        }
                    }
                }
            }

            cashheader.SetGenerateCashBookTransfer("Y");
            if (!cashheader.Save())
            {
                log.Severe("NotSaved");
            }
            if (cashtype == i)
            {
                return(Msg.GetMsg(GetCtx(), "NoCashLineExist"));
            }
            return("Completed");
        }
Beispiel #12
0
        protected override bool AfterSave(bool newRecord, bool success)
        {
            #region create default Account
            if (Env.IsModuleInstalled("FRPT_"))
            {
                StringBuilder _sql            = new StringBuilder();
                PO            withholdingAcct = null;
                DataSet       dsAcctSchema    = null;
                DataSet       dsDefaultAcct   = null;

                // get value of "Withholding" -- "related to"
                _sql.Clear();
                _sql.Append(@"SELECT L.Value FROM Ad_Ref_List L INNER JOIN AD_Reference r ON R.AD_REFERENCE_ID=L.AD_REFERENCE_ID 
                                WHERE r.name='FRPT_RelatedTo' AND l.name='Witholding'");
                var relatedtoProduct = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));

                // Get Accounting Schema
                _sql.Clear();
                _sql.Append("SELECT C_AcctSchema_ID FROM C_AcctSchema WHERE IsActive = 'Y' AND AD_CLIENT_ID=" + GetAD_Client_ID());
                dsAcctSchema = DB.ExecuteDataset(_sql.ToString(), null);
                if (dsAcctSchema != null && dsAcctSchema.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < dsAcctSchema.Tables[0].Rows.Count; k++)
                    {
                        // get accounting schema ID
                        int _AcctSchema_ID = Util.GetValueOfInt(dsAcctSchema.Tables[0].Rows[k]["C_AcctSchema_ID"]);

                        // Get Accounting default and combination from "Default Accounting" tab of Accounting schema based on "Related To" (withholding)
                        _sql.Clear();
                        _sql.Append(@"SELECT Frpt_Acctdefault_Id,C_Validcombination_Id FROM Frpt_Acctschema_Default
                                        WHERE ISACTIVE='Y' AND AD_CLIENT_ID=" + GetAD_Client_ID() + "AND C_Acctschema_Id=" + _AcctSchema_ID +
                                    " AND Frpt_Relatedto = " + relatedtoProduct);
                        dsDefaultAcct = DB.ExecuteDataset(_sql.ToString(), null, Get_Trx());
                        if (dsDefaultAcct != null && dsDefaultAcct.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < dsDefaultAcct.Tables[0].Rows.Count; i++)
                            {
                                // check record exist or not, if not then create it
                                _sql.Clear();
                                _sql.Append(@"Select COUNT(Bp.C_Withholding_ID) From C_Withholding Bp
                                                       Left Join FRPT_Withholding_Acct  ca On Bp.C_Withholding_ID=ca.C_Withholding_ID 
                                                        And ca.Frpt_Acctdefault_Id=" + dsDefaultAcct.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]
                                            + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + GetAD_Client_ID() +
                                            " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(dsDefaultAcct.Tables[0].Rows[i]["C_Validcombination_Id"]) +
                                            " AND Bp.C_Withholding_ID = " + GetC_Withholding_ID());
                                int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                if (recordFound == 0)
                                {
                                    withholdingAcct = MTable.GetPO(GetCtx(), "FRPT_Withholding_Acct", 0, null);
                                    withholdingAcct.Set_ValueNoCheck("AD_Org_ID", 0);
                                    withholdingAcct.Set_ValueNoCheck("C_Withholding_ID", Util.GetValueOfInt(GetC_Withholding_ID()));
                                    withholdingAcct.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(dsDefaultAcct.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                    withholdingAcct.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(dsDefaultAcct.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                    withholdingAcct.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                    if (!withholdingAcct.Save())
                                    {
                                        ValueNamePair pp = VLogger.RetrieveError();
                                        log.Log(Level.SEVERE, "Could Not create FRPT_Asset_Groip_Acct. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            return(true);
        }
Beispiel #13
0
        /// <summary>
        /// To copy the task lines from project template Standard Task lines tab
        /// </summary>
        /// <param name="Task_ID">ID of tasks</param>
        /// <param name="C_ProjectTask_ID">Project task ID</param>
        /// <returns>No of lines created</returns>
        public int CopyMTaskLinesFromProjectTask(MProjectTask fromTask, MProjectTask toTask, int To_Project_ID)
        {
            ValueNamePair pp            = null;
            int           tasklinecount = 0;
            StringBuilder msg           = new StringBuilder();

            try
            {
                MProjectLine[]      fromLines = null;
                List <MProjectLine> list      = new List <MProjectLine>();

                DataSet projDs = DB.ExecuteDataset(" SELECT C_ProjectLine_ID FROM C_ProjectLine WHERE " +
                                                   " C_ProjectPhase_ID =" + fromTask.GetC_ProjectPhase_ID() + " AND C_ProjectTask_ID =" + fromTask.GetC_ProjectTask_ID() +
                                                   " AND IsActive='Y' ORDER BY Line ");

                if (projDs != null && projDs.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < projDs.Tables[0].Rows.Count; k++)
                    {
                        list.Add(new MProjectLine(GetCtx(), Util.GetValueOfInt(projDs.Tables[0].Rows[k]["C_ProjectLine_ID"]), Get_TrxName()));
                    }
                    fromLines = new MProjectLine[list.Count];
                    fromLines = list.ToArray();
                }

                if (fromLines != null && fromLines.Length > 0)
                {
                    for (int j = 0; j < fromLines.Length; j++)
                    {
                        MProjectLine line = new MProjectLine(GetCtx(), 0, Get_TrxName());
                        PO.CopyValues(fromLines[j], line, GetAD_Client_ID(), GetAD_Org_ID());
                        line.SetC_Project_ID(To_Project_ID);
                        line.SetC_ProjectTask_ID(toTask.GetC_ProjectTask_ID());
                        line.SetC_ProjectPhase_ID(toTask.GetC_ProjectPhase_ID());
                        line.SetInvoicedAmt(Env.ZERO);
                        line.SetInvoicedQty(Env.ZERO);
                        line.SetC_OrderPO_ID(0);
                        line.SetC_Order_ID(0);
                        line.SetProcessed(false);
                        if (line.Save())
                        {
                            tasklinecount++;
                        }
                        else
                        {
                            pp = VLogger.RetrieveError();
                            if (pp != null)
                            {
                                msg.Append(pp.GetName());
                                //if GetName is Empty then it will check GetValue
                                if (string.IsNullOrEmpty(msg.ToString()))
                                {
                                    msg.Append(Msg.GetMsg("", pp.GetValue()));
                                }
                            }
                            if (string.IsNullOrEmpty(msg.ToString()))
                            {
                                msg.Append(Msg.GetMsg(GetCtx(), "VIS_LineNotSaved"));
                            }
                            else
                            {
                                msg.Append(Msg.GetMsg(GetCtx(), "VIS_LineNotSaved") + "," + msg.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, "", ex);
            }
            //
            return(tasklinecount);
        }
Beispiel #14
0
        /// <summary>
        /// To copy task from other phase to new phase
        /// </summary>
        /// <param name="fromPhase">From Phase</param>
        /// <param name="toPhase">To Phase</param>
        /// <returns></returns>
        public int CopyTasksFrom(MProjectPhase fromPhase, MProjectPhase toPhase)
        {
            if (fromPhase == null)
            {
                return(0);
            }
            int           count = 0;
            ValueNamePair pp = null; StringBuilder msg = new StringBuilder();

            MProjectTask[] myTasks = GetTasks();
            MProjectTask[] fromTasks = fromPhase.GetTasks();
            int            C_Task_ID = 0; bool exists = false;

            //	Copy Project Tasks
            for (int i = 0; i < fromTasks.Length; i++)
            {
                //	Check if Task already exists
                C_Task_ID = fromTasks[i].GetC_ProjectTask_ID();
                exists    = false;
                if (C_Task_ID == 0)
                {
                    exists = false;
                }
                else
                {
                    for (int ii = 0; ii < myTasks.Length; ii++)
                    {
                        if (myTasks[ii].GetC_ProjectTask_ID() == C_Task_ID)
                        {
                            exists = true;
                            break;
                        }
                    }
                }
                //	Phase exist
                if (exists)
                {
                    log.Info("Task already exists here, ignored - " + fromTasks[i]);
                }
                else
                {
                    MProjectTask toTask = new MProjectTask(GetCtx(), 0, Get_TrxName());
                    PO.CopyValues(fromTasks[i], toTask, GetAD_Client_ID(), GetAD_Org_ID());
                    toTask.SetC_ProjectPhase_ID(toPhase.GetC_ProjectPhase_ID());
                    if (toTask.Save())
                    {
                        count++;
                        count += CopyMTaskLinesFromProjectTask(fromTasks[i], toTask, toPhase.GetC_Project_ID());
                    }
                    else
                    {
                        pp = VLogger.RetrieveError();
                        if (pp != null)
                        {
                            msg.Append(pp.GetName());
                            //if GetName is Empty then it will check GetValue
                            if (string.IsNullOrEmpty(msg.ToString()))
                            {
                                msg.Append(Msg.GetMsg("", pp.GetValue()));
                            }
                        }
                        if (string.IsNullOrEmpty(msg.ToString()))
                        {
                            msg.Append(Msg.GetMsg(GetCtx(), "VIS_LineNotSaved"));
                        }
                        else
                        {
                            msg.Append(Msg.GetMsg(GetCtx(), "VIS_LineNotSaved") + "," + msg.ToString());
                        }
                    }
                }
            }
            if (fromTasks.Length != count)
            {
                log.Warning("Count difference - ProjectPhase=" + fromTasks.Length + " <> Saved=" + count);
            }

            return(count);
        }