コード例 #1
0
 public new bool Equals(object obj)
 {
     //if (obj instanceof ValueNamePair)
     if (typeof(object) == obj.GetType())
     {
         ValueNamePair pp = (ValueNamePair)obj;
         if (pp.GetName() != null && pp.GetValue() != null &&
             pp.GetName().Equals(GetName()) && pp.GetValue().Equals(_value))
         {
             return(true);
         }
         return(false);
     }
     return(false);
 }
コード例 #2
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 CopyMTaskLines(int Task_ID, int C_ProjectTask_ID)
        {
            MProjectLine  taskline      = null;
            ValueNamePair pp            = null;
            int           tasklinecount = 0;
            StringBuilder msg           = new StringBuilder();
            String        sql           = "SELECT M_Product_ID, Description, StandardQty, SeqNo FROM C_TaskLine WHERE IsActive='Y' AND C_Task_ID =" + Task_ID + " ORDER BY SeqNo";

            try
            {
                DataSet ds = DataBase.DB.ExecuteDataset(sql, null, Get_TrxName());
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        taskline = new MProjectLine(GetCtx(), 0, Get_TrxName());
                        taskline.SetC_ProjectTask_ID(C_ProjectTask_ID);
                        taskline.SetDescription(Util.GetValueOfString(ds.Tables[0].Rows[i]["Description"]));
                        taskline.SetM_Product_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["M_Product_ID"]));
                        taskline.SetPlannedQty(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["StandardQty"]));
                        taskline.Set_ValueNoCheck("TaskLineNo", Util.GetValueOfInt(ds.Tables[0].Rows[i]["SeqNo"]));
                        if (taskline.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_TaskLineNotSaved"));
                            }
                            else
                            {
                                msg.Append(Msg.GetMsg(GetCtx(), "VIS_TaskLineNotSaved") + "," + msg.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, sql, ex);
            }
            //
            return(tasklinecount);
        }
        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");
        }
コード例 #4
0
        /// <summary>
        /// To copy details from one project to another
        /// </summary>
        /// <param name="fromProject">From Project</param>
        /// <param name="toProject">To Project</param>
        /// <returns>No Of Lines copied</returns>
        public int CopyDetailsFrom(MProject fromProject, MProject toProject)
        {
            if (IsProcessed() || fromProject == null || toProject == null)
            {
                return(0);
            }
            int count = 0; ValueNamePair pp = null; StringBuilder msg = new StringBuilder();

            #region create lines for project
            if (toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_Project))
            {
                MProjectLine[] fromLines = fromProject.GetLines();
                MProjectLine   line      = null;
                for (int i = 0; i < fromLines.Length; i++)
                {
                    line = new MProjectLine(GetCtx(), 0, fromProject.Get_TrxName());
                    PO.CopyValues(fromLines[i], line, GetAD_Client_ID(), GetAD_Org_ID());
                    line.SetC_Project_ID(toProject.GetC_Project_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())
                    {
                        count++;
                    }
                    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());
                        }
                    }
                }
            }
            #endregion

            if (toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_Phase) || toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_Task) ||
                toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_TaskLine))
            {
                #region if project line level is Project then create lines for phase only
                MProjectPhase[]     myPhases = GetPhases();
                MProjectPhase[]     fromPhases = fromProject.GetPhases();
                int                 C_Phase_ID = 0; bool exists = false;
                MProjectPhase       toPhase   = null;
                MProjectLine[]      fromLines = null;
                List <MProjectLine> list      = null;
                //	Copy Phases
                for (int i = 0; i < fromPhases.Length; i++)
                {
                    //	Check if Phase already exists
                    C_Phase_ID = fromPhases[i].GetC_Phase_ID();
                    exists     = false;
                    if (C_Phase_ID == 0)
                    {
                        exists = false;
                    }
                    else
                    {
                        for (int ii = 0; ii < myPhases.Length; ii++)
                        {
                            if (myPhases[ii].GetC_Phase_ID() == C_Phase_ID)
                            {
                                exists = true;
                                break;
                            }
                        }
                    }
                    //	Phase exist
                    if (exists)
                    {
                        log.Info("Phase already exists here, ignored - " + fromPhases[i]);
                    }
                    else
                    {
                        toPhase = new MProjectPhase(GetCtx(), 0, Get_TrxName());
                        PO.CopyValues(fromPhases[i], toPhase, GetAD_Client_ID(), GetAD_Org_ID());
                        toPhase.SetC_Project_ID(toProject.GetC_Project_ID());
                        toPhase.SetC_Order_ID(0);
                        toPhase.SetIsComplete(false);
                        if (toPhase.Save())
                        {
                            count++;
                            if (toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_Task) || toProject.GetProjectLineLevel().Equals(PROJECTLINELEVEL_TaskLine))
                            {
                                toPhase.CopyTasksFrom(fromPhases[i], toPhase);
                            }
                            else
                            {
                                DataSet projDs = DB.ExecuteDataset(" SELECT C_ProjectLine_ID FROM C_ProjectLine WHERE " +
                                                                   " C_ProjectPhase_ID=" + fromPhases[i].GetC_ProjectPhase_ID() + " AND " +
                                                                   " C_Project_ID = " + fromPhases[i].GetC_Project_ID() + " ORDER BY Line ");

                                if (projDs != null && projDs.Tables[0].Rows.Count > 0)
                                {
                                    list = new List <MProjectLine>();
                                    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)
                                {
                                    MProjectLine line = null;
                                    for (int j = 0; j < fromLines.Length; j++)
                                    {
                                        line = new MProjectLine(GetCtx(), 0, fromProject.Get_TrxName());
                                        PO.CopyValues(fromLines[j], line, GetAD_Client_ID(), GetAD_Org_ID());
                                        line.SetC_Project_ID(toProject.GetC_Project_ID());
                                        line.SetC_ProjectPhase_ID(toPhase.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())
                                        {
                                            count++;
                                        }
                                        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());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        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());
                            }
                        }
                    }
                }
                #endregion
            }



            //    count = CopyLinesFrom(fromProject)
            //+ CopyPhasesFrom(fromProject);
            return(count);
        }
コード例 #5
0
 protected override bool AfterSave(bool newRecord, bool success)
 {
     //by Amit - 6-5-2016
     if (newRecord)
     {
         string sql = @"SELECT COUNT(*) FROM C_Conversion_Rate WHERE ISActive = 'Y' AND c_currency_id = " + GetC_Currency_To_ID() +
                      " AND C_Currency_To_ID = " + GetC_Currency_ID() + " AND c_conversiontype_id = " + GetC_ConversionType_ID() +
                      " AND ( ValidFrom BETWEEN " + GlobalVariable.TO_DATE(GetValidFrom(), true) + " AND " + GlobalVariable.TO_DATE(GetValidTo(), true) +
                      " OR ValidTo BETWEEN " + GlobalVariable.TO_DATE(GetValidFrom(), true) + " AND " + GlobalVariable.TO_DATE(GetValidTo(), true) + " ) " +
                      " AND AD_Client_ID = " + GetAD_Client_ID();
         if (Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_Trx())) <= 0)
         {
             MConversionRate conRate = new MConversionRate(GetCtx(), 0, null);
             conRate.SetAD_Client_ID(GetAD_Client_ID());
             conRate.UpdateFromServer = false;
             conRate.SetAD_Org_ID(GetAD_Org_ID());
             conRate.SetC_Currency_ID(GetC_Currency_To_ID());
             conRate.SetC_Currency_To_ID(GetC_Currency_ID());
             conRate.SetC_ConversionType_ID(GetC_ConversionType_ID());
             conRate.SetDivideRate(GetMultiplyRate());
             conRate.SetMultiplyRate(GetDivideRate());
             conRate.SetValidFrom(GetValidFrom());
             conRate.SetValidTo(GetValidTo());
             if (!conRate.Save(Get_Trx()))
             {
                 ValueNamePair pp = VLogger.RetrieveError();
                 log.Info("Conversion Rate not saved : " + pp.GetValue() + " AND " + pp.GetName());
             }
         }
     }
     //end
     return(true);
 }
コード例 #6
0
        protected override bool AfterSave(bool newRecord, bool success)
        {
            // create default Account
            StringBuilder _sql = new StringBuilder();

            _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() + "'");
            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='Asset'");
                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 A_Asset_Group Bp
                                                       Left Join FRPT_Asset_Group_Acct  ca On Bp.A_Asset_Group_ID=ca.A_Asset_Group_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.A_Asset_Group_ID = " + GetA_Asset_Group_ID());
                                    int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                    if (recordFound == 0)
                                    {
                                        assetGroupAcct = MTable.GetPO(GetCtx(), "FRPT_Asset_Group_Acct", 0, null);
                                        assetGroupAcct.Set_ValueNoCheck("AD_Org_ID", 0);
                                        assetGroupAcct.Set_ValueNoCheck("A_Asset_Group_ID", Util.GetValueOfInt(GetA_Asset_Group_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);
        }
コード例 #7
0
        /// <summary>
        /// Process Allocation (does not update line).
        /// - Update and Link Invoice/Payment/Cash
        /// </summary>
        /// <param name="reverse">reverse if true allocation is reversed</param>
        /// <returns>C_BPartner_ID</returns>
        public int ProcessIt(bool reverse)
        {
            log.Fine("Reverse=" + reverse + " - " + ToString());
            int C_Invoice_ID = GetC_Invoice_ID();
            MInvoicePaySchedule invoiceSchedule = null;
            MPayment            payment         = null;
            MCashLine           cashLine        = null;
            MInvoice            invoice         = GetInvoice();

            if (invoice != null &&
                GetC_BPartner_ID() != invoice.GetC_BPartner_ID())
            {
                SetC_BPartner_ID(invoice.GetC_BPartner_ID());
            }
            //
            int C_Payment_ID  = GetC_Payment_ID();
            int C_CashLine_ID = GetC_CashLine_ID();

            //	Update Payment
            if (C_Payment_ID != 0)
            {
                payment = new MPayment(GetCtx(), C_Payment_ID, Get_TrxName());
                if (GetC_BPartner_ID() != payment.GetC_BPartner_ID())
                {
                    log.Warning("C_BPartner_ID different - Invoice=" + GetC_BPartner_ID() + " - Payment=" + payment.GetC_BPartner_ID());
                }
                if (reverse)
                {
                    if (!payment.IsCashTrx())
                    {
                        payment.SetIsAllocated(false);
                        payment.Save();
                    }
                }
                else
                {
                    if (payment.TestAllocation())
                    {
                        payment.Save();
                    }
                }
            }

            //	Update Cash Journal
            if (C_CashLine_ID != 0)
            {
                cashLine = new MCashLine(GetCtx(), C_CashLine_ID, Get_TrxName());
                if (GetC_BPartner_ID() != cashLine.GetC_BPartner_ID())
                {
                    log.Warning("C_BPartner_ID different - Invoice=" + GetC_BPartner_ID() + " - CashJournal=" + cashLine.GetC_BPartner_ID());
                }
                if (reverse)
                {
                    cashLine.SetIsAllocated(false);
                    if (!cashLine.Save(Get_Trx()))
                    {
                        ValueNamePair pp = VLogger.RetrieveError();
                        log.Log(Level.SEVERE, "Error found for updating cashLine  for  this Line ID = " + cashLine.GetC_CashLine_ID() +
                                " Error Name is " + pp.GetName() + " And Error Type is " + pp.GetType());
                    }
                }
            }

            //	Payment - Invoice
            if (C_Payment_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_Payment_ID(0);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                }
                else if (invoice.IsPaid())
                {
                    invoice.SetC_Payment_ID(C_Payment_ID);
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_Payment_ID="
                                + (reverse ? "NULL " : "(SELECT C_Payment_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_Payment_ID=" + C_Payment_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            //	Cash - Invoice
            if (C_CashLine_ID != 0 && invoice != null)
            {
                //	Link to Invoice
                if (reverse)
                {
                    invoice.SetC_CashLine_ID(0);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
                    // Set isallocated false on cashline while allocation gets deallocated assigned by Mukesh sir on 27/12/2017
                    //MCashLine cashline = new MCashLine(GetCtx(), GetC_CashLine_ID(), Get_TrxName());
                    //cashline.SetIsAllocated(false);
                    //cashline.Save();
                }
                else
                {
                    invoice.SetC_CashLine_ID(C_CashLine_ID);
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + " Linked to C_Invoice_ID=" + C_Invoice_ID);
                }

                //	Link to Order
                String update = "UPDATE C_Order o "
                                + "SET C_CashLine_ID="
                                + (reverse ? "NULL " : "(SELECT C_CashLine_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
                                + "WHERE EXISTS (SELECT * FROM C_Invoice i "
                                + "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
                if (DataBase.DB.ExecuteQuery(update, null, Get_TrxName()) > 0)
                {
                    log.Fine("C_CashLine_ID=" + C_CashLine_ID
                             + (reverse ? " UnLinked from" : " Linked to")
                             + " order of C_Invoice_ID=" + C_Invoice_ID);
                }
            }

            if (GetGL_JournalLine_ID() != 0 && reverse)
            {
                // set allocation as false on View Allocation reversal
                DB.ExecuteQuery(@" UPDATE GL_JOURNALLINE SET isAllocated ='N' WHERE GL_JOURNALLINE_ID =" + GetGL_JournalLine_ID(), null, Get_TrxName());
            }
            // Added by Bharat- Update Discrepancy amount on Invoice.

            if (C_Payment_ID == 0 && C_CashLine_ID == 0 && invoice != null)
            {
                if (invoice.Get_ColumnIndex("DiscrepancyAmt") >= 0)
                {
                    decimal desAmt     = invoice.GetDiscrepancyAmt();
                    decimal desAjusted = invoice.GetDiscrepancyAdjusted();
                    decimal allocAmt   = Math.Abs(GetAmount()); //	absolute
                    if (reverse)
                    {
                        if (allocAmt > desAjusted)
                        {
                            desAmt     = Decimal.Add(desAjusted, desAmt);
                            desAjusted = 0;
                        }
                        else
                        {
                            desAmt     = Decimal.Add(desAmt, allocAmt);
                            desAjusted = Decimal.Subtract(desAjusted, allocAmt);
                        }

                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt > 0)
                        {
                            invoice.SetIsInDispute(true);
                        }
                    }
                    else
                    {
                        if (allocAmt > desAmt)
                        {
                            desAjusted = Decimal.Add(desAjusted, desAmt);
                            desAmt     = 0;
                        }
                        else
                        {
                            desAjusted = Decimal.Add(desAjusted, allocAmt);
                            desAmt     = Decimal.Subtract(desAmt, allocAmt);
                        }
                        invoice.SetDiscrepancyAmt(desAmt);
                        invoice.SetDiscrepancyAdjusted(desAjusted);
                        if (desAmt == 0)
                        {
                            invoice.SetIsInDispute(false);
                        }
                    }
                    if (!invoice.Save())
                    {
                        log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                    }
                }
            }

            //	Update Balance / Credit used - Counterpart of MInvoice.completeIt
            if (invoice != null)
            {
                if (invoice.TestAllocation() && !invoice.Save())
                {
                    log.Log(Level.SEVERE, "Invoice not updated - " + invoice);
                }
                else if (reverse)
                {
                    // added by Amit
                    // if payment Management module downloaded and Invoice Schedule id available on Allocation then mark ispaid on schedule as false
                    if (Env.IsModuleInstalled("VA009_"))
                    {
                        MAllocationHdr allocHdr = new MAllocationHdr(GetCtx(), GetC_AllocationHdr_ID(), Get_Trx());
                        decimal        payAmt   = 0;
                        MDocType       doctype  = null;
                        MCurrency      currency = new MCurrency(GetCtx(), invoice.GetC_Currency_ID(), null);
                        if (GetC_InvoicePaySchedule_ID() != 0 && !invoice.IsPaid())
                        {
                            invoiceSchedule = new MInvoicePaySchedule(GetCtx(), GetC_InvoicePaySchedule_ID(), Get_TrxName());
                            invoiceSchedule.SetVA009_IsPaid(false);
                            // when we update schedule paid as False, then update payment method and related fields on schedule as on Invoice Header
                            if (reverse)
                            {
                                invoiceSchedule.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID());
                                DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE IsActive = 'Y' AND  VA009_PaymentMethod_ID = " + invoice.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"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                                    }
                                    if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                                    {
                                        invoiceSchedule.SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                                    }
                                    invoiceSchedule.SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                                }
                                dsPaymentMethod = null;
                            }
                            if (reverse && payment != null)
                            {
                                #region Handle for Payment & Invoice Allocation
                                doctype = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);

                                // convert (payment amount / Amount from View Allocation) to invoice currency amount then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "APC")
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when payment created with invoice refernce direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add((payment.GetPayAmt() +
                                                                                                                           (payment.Get_ColumnIndex("BackupWithholdingAmount") >= 0 ? (payment.GetWithholdingAmt() + payment.GetBackupWithholdingAmount()) : 0)), payment.GetDiscountAmt()),
                                                                                                              payment.GetWriteOffAmt())), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry OR
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()),
                                                                                                              GetWriteOffAmt())), allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                         invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "APC")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                else
                                {
                                    if (payment.GetC_Invoice_ID() != 0)
                                    {
                                        // when we create payment with invoice reference direct
                                        // convert payment amount in invoice amt with payment date and payment conversion type
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add((payment.GetPayAmt() +
                                                                                                            (payment.Get_ColumnIndex("BackupWithholdingAmount") >= 0 ? (payment.GetWithholdingAmt() + payment.GetBackupWithholdingAmount()) : 0)), payment.GetDiscountAmt()),
                                                                                               payment.GetWriteOffAmt()), payment.GetC_Currency_ID(), invoice.GetC_Currency_ID(), payment.GetDateAcct(),
                                                                         payment.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    }
                                    else
                                    {
                                        // when payment created with Payment Allocate entry Or
                                        // when we match payment with invoice through Payment Allocation form
                                        // convert payment amount in invoice amt with view allocation date
                                        payAmt = MConversionRate.Convert(GetCtx(), Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()),
                                                                         allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(), invoice.GetC_ConversionType_ID(),
                                                                         GetAD_Client_ID(), GetAD_Org_ID());
                                        if (doctype.GetDocBaseType() == "API")
                                        {
                                            payAmt = Decimal.Negate(payAmt);
                                        }
                                    }
                                }
                                invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                     currency.GetStdPrecision()));

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of Payment from schedule
                                invoiceSchedule.SetC_Payment_ID(0);

                                #endregion
                            }
                            else if (reverse && C_CashLine_ID > 0)
                            {
                                #region Handle fo Cash Journal & Invoice Allocation

                                doctype  = new MDocType(GetCtx(), invoice.GetC_DocType_ID(), null);
                                cashLine = new MCashLine(GetCtx(), C_CashLine_ID, Get_Trx());

                                // convert cash amount to invoice currency amount with allocation date then subtract Paid invoice amount to calculated amount
                                if (doctype.GetDocBaseType() == "ARC" || doctype.GetDocBaseType() == "API")
                                {
                                    payAmt = Decimal.Negate(Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt()));
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }
                                else
                                {
                                    payAmt = Decimal.Add(Decimal.Add(GetAmount(), GetDiscountAmt()), GetWriteOffAmt());
                                    payAmt = MConversionRate.Convert(GetCtx(), payAmt, allocHdr.GetC_Currency_ID(), invoice.GetC_Currency_ID(), allocHdr.GetDateAcct(),
                                                                     invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID());
                                    invoiceSchedule.SetVA009_PaidAmntInvce(Decimal.Round(Decimal.Subtract(invoiceSchedule.GetVA009_PaidAmntInvce(), payAmt),
                                                                                         currency.GetStdPrecision()));
                                }

                                // during reversal, if Invoice paid amount <> 0 then reduce that amount from next schedule
                                try
                                {
                                    if (invoiceSchedule.GetVA009_PaidAmntInvce() != 0)
                                    {
                                        int no = Util.GetValueOfInt(DB.ExecuteQuery(@"UPDATE C_InvoicePaySchedule 
                                                                 SET VA009_PaidAmntInvce =   NVL(VA009_PaidAmntInvce , 0) + " + Decimal.Round(invoiceSchedule.GetVA009_PaidAmntInvce(), currency.GetStdPrecision()) +
                                                                                    @" , VA009_PaidAmnt =  NVL(VA009_PaidAmnt , 0) + " + Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(), invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()), currency.GetStdPrecision()) +
                                                                                    @" WHERE C_InvoicePaySchedule_ID = ( SELECT MIN(C_InvoicePaySchedule_ID) FROM C_InvoicePaySchedule WHERE IsActive = 'Y'
                                                                 AND VA009_IsPaid = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID() +
                                                                                    @" AND C_InvoicePaySchedule_ID <> " + GetC_InvoicePaySchedule_ID() + " ) ", null, Get_Trx()));

                                        // set paid invoice amount = 0, no > 0 bcz this is not last schedule
                                        if (no > 0)
                                        {
                                            invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                        }
                                    }
                                }
                                catch { }

                                // convert invoice paid amount to base currency amount
                                invoiceSchedule.SetVA009_PaidAmnt(Decimal.Round(MConversionRate.ConvertBase(GetCtx(), invoiceSchedule.GetVA009_PaidAmntInvce(),
                                                                                                            invoice.GetC_Currency_ID(), invoice.GetDateAcct(), invoice.GetC_ConversionType_ID(), GetAD_Client_ID(), GetAD_Org_ID()),
                                                                                currency.GetStdPrecision()));

                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);

                                // remove linking of cash line from schedule
                                invoiceSchedule.SetC_CashLine_ID(0);

                                #endregion
                            }
                            else
                            {
                                invoiceSchedule.SetVA009_PaidAmntInvce(0);
                                invoiceSchedule.SetVA009_PaidAmnt(0);
                                // set Currency Variance amount as 0, when we reverse paymnet/ cash journalor allocation against this schedule
                                invoiceSchedule.SetVA009_Variance(0);
                            }
                            if (!invoiceSchedule.Save(Get_TrxName()))
                            {
                                log.Log(Level.SEVERE, "Invoice Pay Schedule not updated - " + invoice);
                            }
                        }
                    }
                }
            }

            return(GetC_BPartner_ID());
        }
コード例 #8
0
        /// <summary>
        /// Distribute Cost
        /// </summary>
        /// <returns>if success then empty string else message</returns>
        public String DistributeLandedCost()
        {
            // default distribution line
            MExpectedCostDistribution[] _expectedDistributionlines = null;

            // Delete expected distribution lines
            String sql = "DELETE FROM C_ExpectedCostDistribution WHERE  C_ExpectedCost_ID = " + GetC_ExpectedCost_ID();
            int    no  = DataBase.DB.ExecuteQuery(sql, null, Get_Trx());

            if (no != 0)
            {
                _log.Info(" C_ExpectedCostDistribution - Deleted #" + no);
            }

            // get order lines having only product
            MOrderLine[] orderLines = GetLinesItemProduct(GetC_Order_ID());

            // create expected cost distribution lines
            if (orderLines != null && orderLines.Length > 0)
            {
                List <MExpectedCostDistribution> list = new List <MExpectedCostDistribution>();
                for (int i = 0; i < orderLines.Length; i++)
                {
                    MExpectedCostDistribution allocation = new MExpectedCostDistribution(GetCtx(), 0, Get_Trx());
                    allocation.SetC_ExpectedCost_ID(GetC_ExpectedCost_ID());
                    allocation.SetC_OrderLine_ID(orderLines[i].GetC_OrderLine_ID());
                    allocation.SetClientOrg(GetAD_Client_ID(), GetAD_Org_ID());
                    allocation.SetAmt(Env.ZERO);
                    allocation.SetBase(Env.ZERO);
                    allocation.SetQty(Env.ZERO);
                    if (!allocation.Save())
                    {
                        pp = VLogger.RetrieveError();
                        if (pp != null && !string.IsNullOrEmpty(pp.GetName()))
                        {
                            return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved") + ", " + pp.GetName());
                        }
                        else
                        {
                            return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved"));
                        }
                    }
                    else
                    {
                        list.Add(allocation);
                    }
                }
                if (list.Count > 0)
                {
                    _expectedDistributionlines = new MExpectedCostDistribution[list.Count];
                    _expectedDistributionlines = list.ToArray();
                }
            }

            if (_expectedDistributionlines != null && _expectedDistributionlines.Length == 1)
            {
                Decimal baseValue = orderLines[0].GetBase(GetLandedCostDistribution());
                if (baseValue == 0)
                {
                    StringBuilder msgreturn = new StringBuilder("Total of Base values is 0 - ").Append(GetLandedCostDistribution());
                    return(msgreturn.ToString());
                }
                _expectedDistributionlines[0].SetBase(baseValue);
                _expectedDistributionlines[0].SetQty(orderLines[0].GetQtyOrdered());
                _expectedDistributionlines[0].SetAmt(GetAmt(), orderLines[0].GetPrecision());
                if (!_expectedDistributionlines[0].Save())
                {
                    pp = VLogger.RetrieveError();
                    if (pp != null && !string.IsNullOrEmpty(pp.GetName()))
                    {
                        return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved") + ", " + pp.GetName());
                    }
                    else
                    {
                        return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved"));
                    }
                }
            }
            else if (_expectedDistributionlines != null && _expectedDistributionlines.Length > 1)
            {
                // get total
                Decimal total = Env.ZERO;
                for (int i = 0; i < orderLines.Length; i++)
                {
                    total = Decimal.Add(total, orderLines[i].GetBase(GetLandedCostDistribution()));
                }

                if (total == 0)
                {
                    StringBuilder msgreturn = new StringBuilder("Total of Base values is 0 - ").Append(GetLandedCostDistribution());
                    return(msgreturn.ToString());
                }

                //	Create Allocations
                for (int i = 0; i < _expectedDistributionlines.Length; i++)
                {
                    MOrderLine orderLine = new MOrderLine(GetCtx(), _expectedDistributionlines[i].GetC_OrderLine_ID(), Get_Trx());
                    Decimal    baseValue = orderLine.GetBase(GetLandedCostDistribution());
                    _expectedDistributionlines[i].SetBase(baseValue);
                    _expectedDistributionlines[i].SetQty(orderLine.GetQtyOrdered());
                    if (baseValue != 0)
                    {
                        Decimal result = Decimal.Multiply(GetAmt(), baseValue);
                        result = Decimal.Round(Decimal.Divide(result, total), orderLine.GetPrecision(), MidpointRounding.AwayFromZero);
                        _expectedDistributionlines[i].SetAmt(result);
                    }
                    if (!_expectedDistributionlines[i].Save())
                    {
                        pp = VLogger.RetrieveError();
                        if (pp != null && !string.IsNullOrEmpty(pp.GetName()))
                        {
                            return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved") + ", " + pp.GetName());
                        }
                        else
                        {
                            return(Msg.GetMsg(GetCtx(), "ExpectedAllocationNotSaved"));
                        }
                    }
                }
            }
            AllocateLandedCostRounding(_expectedDistributionlines);
            return("");
        }
コード例 #9
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);
        }
コード例 #10
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
コード例 #11
0
        }       //	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
コード例 #12
0
        /// <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);
        }
コード例 #13
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");
        }
コード例 #14
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);
        }
コード例 #15
0
        public static bool InsertForeignCostAverageInvoice(Ctx ctx, MInvoice invoice, MInvoiceLine invoiceLine, Trx trx)
        {
            int                  acctSchema_ID    = 0;
            int                  M_CostElement_ID = 0;
            int                  AD_Org_ID        = 0;
            int                  M_ASI_ID         = 0;
            MProduct             product          = null;
            MAcctSchema          acctSchema       = null;
            MCostForeignCurrency foreignCost      = null;
            dynamic              pc = null;
            String               cl = null;

            try
            {
                // if cost is calculated then not to calculate again
                if (invoiceLine.IsFutureCostCalculated())
                {
                    return(true);
                }

                acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci
                                    ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id  = " + invoice.GetAD_Client_ID()));
                acctSchema    = new MAcctSchema(ctx, acctSchema_ID, trx);

                if (acctSchema.GetC_Currency_ID() != invoice.GetC_Currency_ID())
                {
                    // Get Costing Element of Av. Invoice
                    M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = "
                                                                           + invoice.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'I'"));

                    product = new MProduct(ctx, invoiceLine.GetM_Product_ID(), trx);

                    if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product
                    {
                        pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID());

                        // Get Costing Level
                        if (pc != null)
                        {
                            cl = pc.GetCostingLevel();
                        }
                        if (cl == null)
                        {
                            cl = acctSchema.GetCostingLevel();
                        }

                        if (cl == "C" || cl == "B")
                        {
                            AD_Org_ID = 0;
                        }
                        else
                        {
                            AD_Org_ID = invoice.GetAD_Org_ID();
                        }
                        if (cl != "B")
                        {
                            M_ASI_ID = 0;
                        }
                        else
                        {
                            M_ASI_ID = invoiceLine.GetM_AttributeSetInstance_ID();
                        }

                        foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, invoice.GetC_BPartner_ID(), invoice.GetC_Currency_ID());
                        foreignCost.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                        foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), invoiceLine.GetQtyInvoiced()));
                        foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), invoiceLine.GetLineNetAmt()));
                        if (foreignCost.GetCumulatedQty() != 0)
                        {
                            foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision()));
                        }
                        else
                        {
                            foreignCost.SetCostPerUnit(0);
                        }
                        if (!foreignCost.Save(trx))
                        {
                            ValueNamePair pp = VLogger.RetrieveError();
                            _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() +
                                        " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() +
                                        " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID());
                            return(false);
                        }
                        else
                        {
                            invoiceLine.SetIsFutureCostCalculated(true);
                            if (!invoiceLine.Save(trx))
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Severe("Error occured during updating Is Foreign Cost On C_invoice. Error name : " + pp.GetName() +
                                            " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() +
                                            " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID());
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, "", ex);
                return(false);
            }
            return(true);
        }
コード例 #16
0
        /// <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);
        }
コード例 #17
0
        public static bool InsertForeignCostMatchOrder(Ctx ctx, MOrderLine orderLine, decimal matchQty, int ASI, Trx trx)
        {
            int                  acctSchema_ID    = 0;
            int                  M_CostElement_ID = 0;
            int                  AD_Org_ID        = 0;
            int                  M_ASI_ID         = 0;
            MProduct             product          = null;
            MAcctSchema          acctSchema       = null;
            MCostForeignCurrency foreignCost      = null;
            dynamic              pc    = null;
            String               cl    = null;
            MOrder               order = null;

            try
            {
                order = new MOrder(ctx, orderLine.GetC_Order_ID(), trx);

                if (!order.IsSOTrx() && !order.IsReturnTrx())
                {
                    acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci
                                    ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id  = " + order.GetAD_Client_ID()));
                    acctSchema    = new MAcctSchema(ctx, acctSchema_ID, trx);

                    if (acctSchema.GetC_Currency_ID() != order.GetC_Currency_ID())
                    {
                        // Get Costing Element of Av. PO
                        M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = "
                                                                               + order.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'A'"));

                        product = new MProduct(ctx, orderLine.GetM_Product_ID(), trx);

                        if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product
                        {
                            pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID());

                            // Get Costing Level
                            if (pc != null)
                            {
                                cl = pc.GetCostingLevel();
                            }
                            if (cl == null)
                            {
                                cl = acctSchema.GetCostingLevel();
                            }

                            if (cl == "C" || cl == "B")
                            {
                                AD_Org_ID = 0;
                            }
                            else
                            {
                                AD_Org_ID = order.GetAD_Org_ID();
                            }
                            if (cl != "B")
                            {
                                M_ASI_ID = 0;
                            }
                            else
                            {
                                M_ASI_ID = ASI;
                            }

                            foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, order.GetC_BPartner_ID(), order.GetC_Currency_ID());
                            foreignCost.SetC_Order_ID(order.GetC_Order_ID());
                            foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), matchQty));
                            foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), Decimal.Multiply(orderLine.GetPriceActual(), matchQty)));
                            if (foreignCost.GetCumulatedQty() != 0)
                            {
                                foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision()));
                            }
                            else
                            {
                                foreignCost.SetCostPerUnit(0);
                            }
                            if (!foreignCost.Save(trx))
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() +
                                            " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + orderLine.GetC_OrderLine_ID() +
                                            " , AND Ad_Client_ID : " + orderLine.GetAD_Client_ID());
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, "", ex);
                return(false);
            }
            return(true);
        }
コード例 #18
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);
        }