Exemplo n.º 1
0
        private PO GetPO(string tableName, int recordID, Ctx ctx)
        {
            //throw new NotImplementedException();
            MTable table = MTable.Get(ctx, Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Table_ID FROM AD_Table WHERE TableName='" + tableName + "'")));

            return(table.GetPO(ctx, recordID, null));
        }
        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (variables are parsed)</returns>
        protected override String DoIt()
        {
            MWFProcess process = new MWFProcess(GetCtx(), p_AD_WF_Process_ID, Get_Trx());

            log.Info("doIt - " + process);

            MUser user = MUser.Get(GetCtx(), GetAD_User_ID());

            //	Abort
            if (p_IsAbort)
            {
                msg = user.GetName() + ": Abort";
                process.SetTextMsg(msg);
                process.SetAD_User_ID(GetAD_User_ID());
                process.SetWFState(StateEngine.STATE_ABORTED);

                //JID_0278 : To mark processing checkbox false.
                // Mohit
                // Date : 22 May 2019
                MTable table = new MTable(GetCtx(), process.GetAD_Table_ID(), null);
                PO     po    = MTable.GetPO(GetCtx(), table.GetTableName(), process.GetRecord_ID(), Get_Trx());
                if (po != null && po.Get_ColumnIndex("Processing") >= 0)
                {
                    po.Set_Value("Processing", false);
                    po.Save();
                }
                return(msg);
            }

            //	Change User
            if (p_AD_User_ID != 0 && process.GetAD_User_ID() != p_AD_User_ID)
            {
                MUser from = MUser.Get(GetCtx(), process.GetAD_User_ID());
                MUser to   = MUser.Get(GetCtx(), p_AD_User_ID);
                msg = user.GetName() + ": " + from.GetName() + " -> " + to.GetName();
                process.SetTextMsg(msg);
                process.SetAD_User_ID(p_AD_User_ID);
            }
            //	Change Responsible
            if (p_AD_WF_Responsible_ID != 0 && process.GetAD_WF_Responsible_ID() != p_AD_WF_Responsible_ID)
            {
                MWFResponsible from = MWFResponsible.Get(GetCtx(), process.GetAD_WF_Responsible_ID());
                MWFResponsible to   = MWFResponsible.Get(GetCtx(), p_AD_WF_Responsible_ID);
                String         msg1 = user.GetName() + ": " + from.GetName() + " -> " + to.GetName();
                process.SetTextMsg(msg1);
                process.SetAD_WF_Responsible_ID(p_AD_WF_Responsible_ID);
                if (msg == null)
                {
                    msg = msg1;
                }
                else
                {
                    msg += " - " + msg1;
                }
            }
            process.Save();

            return("OK");
        }
        protected override bool AfterSave(bool newRecord, bool success)
        {
            if (newRecord)
            {
                string Sql        = "SELECT object_name FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND (object_name)  = UPPER('VADMS_TEAM_ACCESS') AND OWNER LIKE '" + DB.GetSchema() + "'";
                string ObjectName = Convert.ToString(DB.ExecuteScalar(Sql));
                if (ObjectName != "")
                {
                    Sql = @"SELECT Distinct AD_Table_ID,record_ID FROM VADMS_Team_Access where C_Team_ID=" + GetC_Team_ID() + " AND IsActive='Y'";
                    DataSet ds = DB.ExecuteDataset(Sql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            //MTable table = MTable.Get(GetCtx(), "VADMS_Team_Access");
                            //PO pos = table.GetPO(GetCtx(), 0, null);

                            //pos.Set_Value("AD_Table_ID", Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Table_ID"]));
                            //pos.Set_Value("AD_User_ID", GetAD_User_ID());
                            //pos.Set_Value("Record_ID", Convert.ToInt32(ds.Tables[0].Rows[i]["Record_ID"]));
                            //pos.Set_Value("C_Team_ID", GetC_Team_ID());
                            //pos.Set_Value("VADMS_Access", "20");
                            //pos.Save();


                            string strQuery = "SELECT VADMS_ACCESS FROM (SELECT record_id,vadms_access,ad_role_id, NULL as AD_USER_ID " +
                                              ",vadms_role_access.vadms_role_access_id,null as vadms_user_access_ID " +
                                              "FROM vadms_role_access WHERE RECORD_ID=" + Convert.ToInt32(ds.Tables[0].Rows[i]["Record_ID"]) + " AND ad_table_id = " + Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Table_ID"]) + "  AND record_id NOT IN" +
                                              "(SELECT record_id FROM vadms_user_access WHERE ad_user_id = " + GetAD_User_ID() + " and ad_table_id = " + Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Table_ID"]) + ") " +

                                              "UNION " +

                                              "SELECT record_id, vadms_access, NULL as AD_Role_ID, AD_USER_ID ,NULL AS vadms_role_access_id,vadms_user_access.vadms_user_access_ID FROM vadms_user_access WHERE RECORD_ID=" + Convert.ToInt32(ds.Tables[0].Rows[i]["Record_ID"]) + " AND ad_user_id = " + GetAD_User_ID() + " and ad_table_id =" + Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Table_ID"]) +
                                              ") ARQ ";

                            int documentAccess = Convert.ToInt32(DB.ExecuteScalar(strQuery));


                            if (documentAccess == 0)
                            {
                                MTable tableUserAccess = MTable.Get(GetCtx(), "VADMS_User_Access");
                                PO     posUserAccess   = tableUserAccess.GetPO(GetCtx(), 0, null);

                                posUserAccess.Set_Value("AD_Table_ID", Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Table_ID"]));
                                posUserAccess.Set_Value("AD_User_ID", GetAD_User_ID());
                                posUserAccess.Set_Value("Record_ID", Convert.ToInt32(ds.Tables[0].Rows[i]["Record_ID"]));
                                posUserAccess.Set_Value("VADMS_Access", "20");
                                posUserAccess.Save();
                            }
                        }
                    }
                }
            }
            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Get Persistent Object
        /// </summary>
        /// <returns>po</returns>
        public PO GetPO()
        {
            if (_po != null)
            {
                return(_po);
            }
            if (GetRecord_ID() == 0)
            {
                return(null);
            }

            MTable table = MTable.Get(GetCtx(), GetAD_Table_ID());

            _po = table.GetPO(GetCtx(), GetRecord_ID(), Get_TrxName());
            return(_po);
        }
Exemplo n.º 5
0
        /// <SUMmary>
        /// Create Product Line details
        /// </SUMmary>
        /// <param name="Parent">C_MasterForecastLine</param>
        /// <param name="Order_ID">Sales Order</param>
        /// <param name="OrderLine_ID">Sales Order line</param>
        /// <param name="Opportunity_ID">Opportunity</param>
        /// <param name="OppLine_ID">Opportunity Line</param>
        /// <param name="Forecast">Team Forecast</param>
        /// <param name="ForecastLine_ID">Forecast Line</param>
        /// <param name="C_Period_ID">Period</param>
        /// <param name="UOM_ID">UOM</param>
        /// <param name="Product_ID">Product</param>
        /// <param name="Quantity">Qunatity</param>
        /// <param name="Price">Price</param>
        /// <param name="M_AttributeSetInstance_ID">Attribute Set Instance</param>
        /// <returns>Product line detail Object</returns>
        private PO GenerateProductLineDetails(MMasterForecastLine Parent, int LineNo, int Order_ID, int OrderLine_ID, int Opportunity_ID, int OppLine_ID, int Forecast, int ForecastLine_ID, int C_Period_ID, int UOM_ID, int Product_ID, Decimal?Quantity, Decimal?Price, int M_AttributeSetInstance_ID)
        {
            //object of VA073_MasterForecastLineDetails
            po = tbl.GetPO(mf.GetCtx(), 0, mf.Get_Trx());
            //LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0) AS DefaultValue FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + Parent.GetC_MasterForecastLine_ID(), null, mf.Get_Trx()));
            po.SetAD_Client_ID(Parent.GetAD_Client_ID());
            po.SetAD_Org_ID(Parent.GetAD_Org_ID());
            po.Set_Value("LineNo", LineNo);
            po.Set_Value("C_MasterForecastLine_ID", Parent.GetC_MasterForecastLine_ID());
            po.Set_Value("C_Order_ID", Order_ID);
            po.Set_Value("C_OrderLine_ID", OrderLine_ID);
            po.Set_Value("C_Project_ID", Opportunity_ID);
            po.Set_Value("C_ProjectLine_ID", OppLine_ID);
            po.Set_Value("C_Forecast_ID", Forecast);
            po.Set_Value("C_ForecastLine_ID", ForecastLine_ID);
            po.Set_Value("C_Period_ID", C_Period_ID);
            po.Set_Value("C_UOM_ID", UOM_ID);
            po.Set_Value("M_Product_ID", Product_ID);
            po.Set_Value("QtyEntered", Quantity);
            po.Set_Value("Price", Price);
            po.Set_Value("M_AttributeSetInstance_ID", M_AttributeSetInstance_ID);

            return(po);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Insert data in Version table against multikey Master table
        /// </summary>
        /// <param name="baseTbl"></param>
        /// <param name="keyCols"></param>
        /// <param name="tblVer"></param>
        /// <returns></returns>
        private string InsertMKVersionData(MTable baseTbl, string[] keyCols, MTable tblVer)
        {
            string retMsg = "";
            // Get data from Master table
            DataSet dsRecs = DB.ExecuteDataset("SELECT * FROM " + baseTbl.GetTableName(), null, _trx);

            // check if there are any records in master table
            if (dsRecs != null && dsRecs.Tables[0].Rows.Count > 0)
            {
                // loop through all records and insert in Version table
                for (int i = 0; i < dsRecs.Tables[0].Rows.Count; i++)
                {
                    // get where Clause for Master table against multiple key columns
                    GetMKWhereClause(dsRecs.Tables[0].Rows[i], keyCols);
                    if (MKWhereClause.Length > 0)
                    {
                        int count = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(" + tblVer.GetTableName() + "_ID) FROM " + tblVer.GetTableName() + " WHERE " + MKWhereClause.ToString(), null, _trx));
                        if (count > 0)
                        {
                            continue;
                        }
                    }

                    // create PO object of source table (Master table)
                    PO sPO = baseTbl.GetPO(GetCtx(), dsRecs.Tables[0].Rows[i], _trx);
                    // create PO object of destination table (Version table)
                    PO dPO = tblVer.GetPO(GetCtx(), 0, _trx);
                    sPO.CopyTo(dPO);
                    dPO.SetAD_Client_ID(sPO.GetAD_Client_ID());
                    dPO.SetAD_Org_ID(sPO.GetAD_Org_ID());
                    dPO.Set_Value("RecordVersion", "1");
                    dPO.Set_ValueNoCheck("VersionValidFrom", sPO.Get_Value("Created"));
                    dPO.Set_ValueNoCheck("IsVersionApproved", true);
                    dPO.Set_ValueNoCheck("Processed", true);
                    dPO.Set_ValueNoCheck("ProcessedVersion", true);
                    for (int j = 0; j < keyCols.Length; j++)
                    {
                        dPO.Set_ValueNoCheck(keyCols[j], sPO.Get_Value(keyCols[j]));
                    }
                    dPO.Set_Value("Export_ID", null);
                    if (!dPO.Save())
                    {
                        ValueNamePair vnp   = VLogger.RetrieveError();
                        string        error = "";
                        if (vnp != null)
                        {
                            error = vnp.GetName();
                            if (error == "" && vnp.GetValue() != null)
                            {
                                error = vnp.GetValue();
                            }
                        }
                        if (error == "")
                        {
                            error = "Error in saving data in Version table";
                        }
                        return(retMsg);
                    }
                }
            }

            return(retMsg);
        }
Exemplo n.º 7
0
        /**
         *  After Save
         *	@param newRecord new
         *	@param success success
         *	@return success
         */
        protected override bool AfterSave(bool newRecord, bool success)
        {
            if (!success)
            {
                return(success);
            }
            VAdvantage.Model.MProduct current = new VAdvantage.Model.MProduct(GetCtx(), GetM_Product_ID(), Get_Trx());
            StringBuilder             _sql    = new StringBuilder("");

            //_sql.Append("Select count(*) from  ad_table where tablename like 'FRPT_Product_Category_Acct'");
            _sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_Product_Category_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                PO obj = null;
                //MFRPTProductAcct obj = null;
                int    _MProduct_ID  = GetM_Product_ID();
                int    _PCategory_ID = GetM_Product_Category_ID();
                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='Product'";
                //"select VALUE from AD_Ref_List where name='Product'";
                string _RelatedToProduct = Convert.ToString(DB.ExecuteScalar(sql));
                //string _RelatedToProduct = X_FRPT_AcctDefault.FRPT_RELATEDTO_Product.ToString();

                _sql.Clear();
                _sql.Append("Select Count(*) From FRPT_Product_Acct  where M_Product_ID=" + _MProduct_ID + " 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_product_category_acct PCA inner join frpt_acctdefault ACC ON acc.frpt_acctdefault_id= PCA.frpt_acctdefault_id where PCA.m_product_category_id=" + _PCategory_ID + " and acc.frpt_relatedto=" + _RelatedToProduct + " AND PCA.IsActive = 'Y' AND PCA.AD_Client_ID = " + GetAD_Client_ID());
                    //_sql.Append("Select C_AcctSchema_ID, C_ValidCombination_ID, FRPT_AcctDefault_ID from FRPT_product_category_acct where m_product_category_id =" + _PCategory_ID);

                    DataSet ds = DB.ExecuteDataset(_sql.ToString());
                    if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            //obj = new MFRPTProductAcct(GetCtx(), 0, null);
                            obj = MTable.GetPO(GetCtx(), "FRPT_Product_Acct", 0, null);
                            obj.Set_ValueNoCheck("AD_Org_ID", 0);
                            obj.Set_ValueNoCheck("M_Product_ID", _MProduct_ID);
                            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())
                            {
                            }
                        }
                    }
                }
                // Change by mohit amortization process
                //int _CountVA038 = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(AD_MODULEINFO_ID) FROM AD_MODULEINFO WHERE PREFIX='VA038_'  AND IsActive = 'Y'"));
                //if (_CountVA038 > 0)
                //{
                //    if (GetProductType() == "E" || GetProductType() == "S")
                //    {
                //        if (Util.GetValueOfInt(Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                //        {
                //            DataSet _dsAcct = DB.ExecuteDataset("SELECT C_AcctSchema_ID, FRPT_AcctDefault_ID, C_VALIDCOMBINATION_ID, SEQNO FROM VA038_Amortization_Acct "
                //                              + "WHERE IsActive='Y' AND  VA038_AmortizationTemplate_ID=" + Util.GetValueOfInt(Get_Value("VA038_AmortizationTemplate_ID")));
                //            if (_dsAcct != null && _dsAcct.Tables[0].Rows.Count > 0)
                //            {
                //                for (int j = 0; j < _dsAcct.Tables[0].Rows.Count; j++)
                //                {
                //                    obj = MTable.GetPO(GetCtx(), "FRPT_Product_Acct", 0, null);
                //                    obj.Set_ValueNoCheck("AD_Org_ID", 0);
                //                    obj.Set_ValueNoCheck("M_Product_ID", _MProduct_ID);
                //                    obj.Set_ValueNoCheck("C_AcctSchema_ID", Util.GetValueOfInt(_dsAcct.Tables[0].Rows[j]["C_AcctSchema_ID"]));
                //                    obj.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(_dsAcct.Tables[0].Rows[j]["C_ValidCombination_ID"]));
                //                    obj.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(_dsAcct.Tables[0].Rows[j]["FRPT_AcctDefault_ID"]));
                //                    if (!obj.Save())
                //                    { }
                //                }
                //            }
                //        }
                //    }
                //}
                // End amortization process
            }
            else
            {
                // By Amit
                //if (!success)
                //    return success;

                //	Value/Name change in Account
                if (!newRecord && (Is_ValueChanged("Value") || Is_ValueChanged("Name")))
                {
                    MAccount.UpdateValueDescription(GetCtx(), "M_Product_ID=" + GetM_Product_ID(), Get_TrxName());
                }

                //	Name/Description Change in Asset	MAsset.setValueNameDescription
                if (!newRecord && (Is_ValueChanged("Name") || Is_ValueChanged("Description")))
                {
                    String sql = " UPDATE A_Asset a SET Name=(SELECT SUBSTR(bp.Name || ' - ' || p.Name,1,60) FROM M_Product p, C_BPartner bp  WHERE p.M_Product_ID=a.M_Product_ID AND bp.C_BPartner_ID=a.C_BPartner_ID)," +
                                 "Description=(SELECT  p.Description FROM M_Product p, C_BPartner bp WHERE p.M_Product_ID=a.M_Product_ID AND bp.C_BPartner_ID=a.C_BPartner_ID)" +
                                 "WHERE IsActive='Y'  AND M_Product_ID=" + GetM_Product_ID();

                    int no = 0;
                    try
                    {
                        no = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, Get_TrxName()));
                    }
                    catch { }
                    log.Fine("Asset Description updated #" + no);
                }
                //	New - Acct, Tree, Old Costing
                if (newRecord)
                {
                    if (String.IsNullOrEmpty(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) || Util.GetValueOfString(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) == "Y")
                    {
                        bool sucs = Insert_Accounting("M_Product_Acct", "M_Product_Category_Acct",
                                                      "p.M_Product_Category_ID=" + GetM_Product_Category_ID());

                        //Karan. work done to show message if data not saved in accounting tab. but will save data in current tab.
                        // Before this, data was being saved but giving message "record not saved".
                        if (!sucs)
                        {
                            log.SaveWarning("AcctNotSaved", "");
                        }
                    }

                    //
                    MAcctSchema[] mass = MAcctSchema.GetClientAcctSchema(GetCtx(), GetAD_Client_ID(), Get_TrxName());
                    for (int i = 0; i < mass.Length; i++)
                    {
                        //	Old
                        MProductCosting pcOld = new MProductCosting(current, mass[i].GetC_AcctSchema_ID());
                        pcOld.Save();
                    }
                }
                //	New Costing
                // by Amit 22-12-2015
                //if (newRecord || Is_ValueChanged("M_Product_Category_ID"))
                //{
                //    MCost.Create(this);
                //}
            }

            //22-12-2015
            //by Amit for creating records ffor product foe all Costing Element whose costing elemnt type is 'Material'
            if (newRecord || Is_ValueChanged("M_Product_Category_ID"))
            {
                MCost.CreateRecords(current);
            }
            //20-12-2016
            //By Vivek Chauhan saving Nutrition value against product...........
            object ModuleId = DB.ExecuteScalar("select ad_moduleinfo_id from ad_moduleinfo where prefix='VA019_' and isactive='Y'");

            if (ModuleId != null && ModuleId != DBNull.Value)
            {
                object objNDBNo = DB.ExecuteScalar("select va019_ndbno from M_Product where m_product_ID=" + GetM_Product_ID() + "");
                if (objNDBNo != null && objNDBNo != DBNull.Value)
                {
                    CallNutritionApi(Convert.ToString(objNDBNo), GetM_Product_ID());
                }
            }

            if (Is_Changed())
            {
                string updatequery = "Update M_Product set GMT01_IsSpoorPosted='N' Where M_Product_ID=" + GetM_Product_ID();
                int    no          = DB.ExecuteQuery(updatequery);
            }

            return(success);
        }
        // Private method called from with the class
        private static void Email()
        {
            // Run this itration infinetly
            try
            {
                while (true)
                {
                    // Get records from mail queue table to send them one by one as email
                    DataSet mailds = DB.ExecuteDataset("SELECT AD_Org_ID, AD_Client_ID, CreatedBy, AD_Role_ID, ToEMail, ToName, MailSubject, MailMessage, IsHtmlEmail, AD_Table_ID, Record_ID, AD_WF_Activity_ID, AD_WF_EventAudit_ID, AD_MailQueue_ID, AD_WF_Process_ID FROM AD_MailQueue WHERE MailStatus = 'Q' AND ROWNUM <= 5 ORDER BY AD_MailQueue_ID");

                    if (mailds != null && mailds.Tables.Count > 0 && mailds.Tables[0].Rows.Count > 0)
                    {
                        for (int m = 0; m < mailds.Tables[0].Rows.Count; m++)
                        {
                            int AD_Org_ID    = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_Org_ID"]);
                            int AD_Client_ID = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_Client_ID"]);
                            int AD_User_ID   = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["CreatedBy"]);
                            int AD_Role_ID   = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_Role_ID"]);

                            String   toEMail             = Util.GetValueOfString(mailds.Tables[0].Rows[m]["ToEMail"]);
                            String   toName              = Util.GetValueOfString(mailds.Tables[0].Rows[m]["ToName"]);
                            String   subject             = Util.GetValueOfString(mailds.Tables[0].Rows[m]["MailSubject"]);
                            String   message             = Util.GetValueOfString(mailds.Tables[0].Rows[m]["MailMessage"]);
                            FileInfo attachment          = null;
                            bool     isHtml              = Util.GetValueOfString(mailds.Tables[0].Rows[m]["IsHtmlEmail"]) == "Y" ? true : false;
                            int      AD_Table_ID         = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_Table_ID"]);
                            int      Record_ID           = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["Record_ID"]);
                            byte[]   array               = null;
                            String   fileName            = null;
                            int      AD_WF_Activity_ID   = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_WF_Activity_ID"]);
                            int      AD_WF_EventAudit_ID = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_WF_EventAudit_ID"]);
                            int      AD_WF_Process_ID    = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_WF_Process_ID"]);
                            int      AD_MailQueue_ID     = Util.GetValueOfInt(mailds.Tables[0].Rows[m]["AD_MailQueue_ID"]);


                            // Create context
                            Ctx _ctx = new Ctx();
                            _ctx.SetAD_Org_ID(AD_Org_ID);
                            _ctx.SetAD_Client_ID(AD_Client_ID);
                            _ctx.SetAD_User_ID(AD_User_ID);
                            _ctx.SetAD_Role_ID(AD_Role_ID);


                            string       sql    = "SELECT AD_WF_NODE_ID FROM AD_WF_Activity WHERE AD_WF_Activity_ID=" + AD_WF_Activity_ID;
                            object       nodeID = DB.ExecuteScalar(sql);
                            X_AD_WF_Node node   = null;

                            if (nodeID != null && nodeID != DBNull.Value)
                            {
                                node = new X_AD_WF_Node(_ctx, Convert.ToInt32(nodeID), null);
                            }
                            FileInfo pdf   = null;
                            MTable   table = MTable.Get(_ctx, AD_Table_ID);
                            PO       po    = table.GetPO(_ctx, Record_ID, null);
                            if (node.IsAttachReport())
                            {
                                VAdvantage.Common.Common com = new Common();
                                pdf = com.GetPdfReportForMail(_ctx, null, AD_Table_ID, Record_ID, AD_User_ID, AD_Client_ID,
                                                              "", 0, AD_WF_Activity_ID);
                            }
                            else if (po is VAdvantage.Process.DocAction)
                            {
                                VAdvantage.Process.DocAction doc = (VAdvantage.Process.DocAction)po;
                                attachment = doc.CreatePDF();
                            }
                            // Check if there is m class for the record and table and fetch attachment from that class
                            //MTable table = MTable.Get(_ctx, AD_Table_ID);
                            //PO po = table.GetPO(_ctx, Record_ID, null);

                            //if (po is VAdvantage.Process.DocAction) // MClass Implement DocAction
                            //{
                            //VAdvantage.Process.DocAction doc = (VAdvantage.Process.DocAction)po;
                            //attachment = doc.CreatePDF();
                            //VAdvantage.Common.Common com = new Common();
                            //FileInfo pdf = com.GetPdfReportForMail(_ctx, null, AD_Table_ID, Record_ID, AD_User_ID, AD_Client_ID,
                            //   "", 0, AD_WF_Activity_ID);
                            if (pdf != null)
                            {
                                array    = File.ReadAllBytes(pdf.FullName);
                                fileName = pdf.Name;
                            }
                            //}

                            // Create Mclient object and send Email
                            MClient client   = MClient.Get(_ctx, AD_Client_ID);
                            bool    mailsent = client.SendEMail(toEMail, toName, subject, message, attachment, isHtml, AD_Table_ID, Record_ID, array, fileName);

                            ViennaAdvantage.Model.X_AD_MailQueue mailQueue = new ViennaAdvantage.Model.X_AD_MailQueue(_ctx, AD_MailQueue_ID, null);

                            if (mailsent)
                            {
                                mailQueue.SetMailStatus("S");
                                int act1 = DB.ExecuteQuery("UPDATE AD_WF_Activity SET WFSTATE = 'CC' WHERE AD_WF_Activity_ID = " + AD_WF_Activity_ID);
                                int aud1 = DB.ExecuteQuery("UPDATE AD_WF_EventAudit SET WFSTATE = 'CC' WHERE AD_WF_EventAudit_ID = " + AD_WF_EventAudit_ID);
                                int wpro = DB.ExecuteQuery("UPDATE AD_WF_Process SET WFSTATE = 'CC' WHERE AD_WF_Process_ID = " + AD_WF_Process_ID + " AND WFState = 'BK' ");
                            }
                            else
                            {
                                mailQueue.SetMailStatus("F");
                                VLogger.Get().Warning("Email not sent by singleton class, marking as failed");
                            }

                            bool mq = mailQueue.Save();

                            // Sleep thread by 1 second to let memory work properly
                            Thread.Sleep(1000);

                            // For testing thread abort problem
                            //thread.Abort();
                        }
                        int deleteoldmails = DB.ExecuteQuery("DELETE FROM AD_MailQueue WHERE (MailStatus = 'S' OR MailStatus = 'F') AND Created <=" + GlobalVariable.TO_DATE(DateTime.Now, false) + " - 7");
                    }
                    else
                    {
                        // Sleep thread by 5 seconds if there is no record in mail queue table
                        Thread.Sleep(60000 * 5);
                    }
                }
            }
            catch (Exception e)
            {
                VLogger.Get().Severe("Error in Email singleton class " + e.Message);
                try
                {
                    // Check if state is not running
                    if (thread.ThreadState != ThreadState.Running)
                    {
                        Thread.ResetAbort();
                    }
                    else
                    {
                        thread.Abort();
                        Thread.ResetAbort();
                    }
                }
                catch (Exception ex)
                { }
                finally
                {
                    thread = null;
                }
            }
        }
Exemplo n.º 9
0
        private PO GetPO(int tableID, int recordID, Ctx ctx)
        {
            MTable table = MTable.Get(ctx, tableID);

            return(table.GetPO(ctx, recordID, null));
        }
Exemplo n.º 10
0
        /**
         *  After Save
         *	@param newRecord new
         *	@param success success
         *	@return success
         */
        //@Override
        protected override Boolean AfterSave(Boolean newRecord, Boolean success)
        {
            int           _client_ID = 0;
            StringBuilder _sql       = new StringBuilder();

            //_sql.Append("Select count(*) from  ad_table where tablename like 'FRPT_Charge_Acct'");
            _sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_Charge_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='Charge'");
                var relatedtoChrge = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));

                PO chrgact = null;
                _client_ID = GetAD_Client_ID();
                _sql.Clear();
                _sql.Append("select C_AcctSchema_ID from C_AcctSchema where AD_CLIENT_ID=" + _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=" + _client_ID + "AND C_Acctschema_Id=" + _AcctSchema_ID);
                        DataSet ds = new DataSet();
                        ds = DB.ExecuteDataset(_sql.ToString(), null);
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                //DataSet ds2 = new DataSet();
                                string _relatedTo = ds.Tables[0].Rows[i]["Frpt_Relatedto"].ToString();
                                if (_relatedTo != "")
                                {
                                    if (_relatedTo == relatedtoChrge)
                                    {
                                        _sql.Clear();
                                        _sql.Append("Select COUNT(*) From C_Charge Bp Left Join Frpt_Charge_Acct ca On Bp.C_Charge_ID=ca.C_Charge_ID And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"] + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + _client_ID + " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]) + " AND Bp.C_Charge_ID = " + GetC_Charge_ID());
                                        int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                        //ds2 = DB.ExecuteDataset(_sql.ToString(), null);
                                        //if (ds2 != null && ds2.Tables[0].Rows.Count > 0)
                                        //{
                                        //    for (int j = 0; j < ds2.Tables[0].Rows.Count; j++)
                                        //    {
                                        //        int value = Util.GetValueOfInt(ds2.Tables[0].Rows[j]["Frpt_Acctdefault_Id"]);
                                        //        if (value == 0)
                                        //        {
                                        //chrgact = new X_FRPT_Charge_Acct(GetCtx(), 0, null);
                                        if (recordFound == 0)
                                        {
                                            chrgact = MTable.GetPO(GetCtx(), "FRPT_Charge_Acct", 0, null);
                                            chrgact.Set_ValueNoCheck("C_Charge_ID", Util.GetValueOfInt(GetC_Charge_ID()));
                                            chrgact.Set_ValueNoCheck("AD_Org_ID", 0);
                                            chrgact.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                            chrgact.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                            chrgact.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                            if (!chrgact.Save())
                                            {
                                            }
                                        }
                                        //        }
                                        //    }
                                        //}
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (newRecord & success && (String.IsNullOrEmpty(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) || Util.GetValueOfString(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) == "Y"))
                {
                    success = Insert_Accounting("C_Charge_Acct", "C_AcctSchema_Default", null);

                    //Karan. work done to show message if data not saved in accounting tab. but will save data in current tab.
                    // Before this, data was being saved but giving message "record not saved".
                    if (!success)
                    {
                        log.SaveWarning("AcctNotSaved", "");
                        return(true);
                    }
                }
            }
            return(success);
        }
Exemplo n.º 11
0
        public DocAtions GetActions(int AD_Table_ID, int Record_ID, string docStatus, bool processing, string orderType, bool isSOTrx, string docAction, string tableName, List <string> _values, List <string> _names)
        {
            DocAtions action = new DocAtions();

            string[] options  = null;
            int      index    = 0;
            string   defaultV = "";

            action.DocStatus = docStatus;

            VLogger.Get().Fine("DocStatus=" + docStatus
                               + ", DocAction=" + docAction + ", OrderType=" + orderType
                               + ", IsSOTrx=" + isSOTrx + ", Processing=" + processing
                               + ", AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID);
            options = new String[_values.Count()];
            String wfStatus = MWFActivity.GetActiveInfo(ctx, AD_Table_ID, Record_ID);

            if (wfStatus != null)
            {
                VLogger.Get().SaveError("WFActiveForRecord", wfStatus);
                action.Error = "WFActiveForRecord";
                return(action);
            }

            //	Status Change
            if (!CheckStatus(tableName, Record_ID, docStatus))
            {
                VLogger.Get().SaveError("DocumentStatusChanged", "");
                action.Error = "DocumentStatusChanged";
                return(action);
            }
            // if (processing != null)
            {
                bool locked = "Y".Equals(processing);
                if (!locked && processing.GetType() == typeof(Boolean))
                {
                    locked = ((Boolean)processing);
                }
                // do not show Unlock action on Production execution
                if (locked && !(AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WrkOdrTransaction.Table_ID))
                {
                    options[index++] = DocumentEngine.ACTION_UNLOCK;
                }
            }

            //	Approval required           ..  NA
            if (docStatus.Equals(DocumentEngine.STATUS_NOTAPPROVED))
            {
                options[index++] = DocumentEngine.ACTION_PREPARE;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	Draft/Invalid				..  DR/IN
            else if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED) ||
                     docStatus.Equals(DocumentEngine.STATUS_INVALID))
            {
                options[index++] = DocumentEngine.ACTION_COMPLETE;
                //	options[index++] = DocumentEngine.ACTION_Prepare;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	In Process                  ..  IP
            else if (docStatus.Equals(DocumentEngine.STATUS_INPROGRESS) ||
                     docStatus.Equals(DocumentEngine.STATUS_APPROVED))
            {
                options[index++] = DocumentEngine.ACTION_COMPLETE;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	Complete                    ..  CO
            else if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
            {
                options[index++] = DocumentEngine.ACTION_CLOSE;
            }
            //	Waiting Payment
            else if (docStatus.Equals(DocumentEngine.STATUS_WAITINGPAYMENT) ||
                     docStatus.Equals(DocumentEngine.STATUS_WAITINGCONFIRMATION))
            {
                options[index++] = DocumentEngine.ACTION_VOID;
                options[index++] = DocumentEngine.ACTION_PREPARE;
            }
            //	Closed, Voided, REversed    ..  CL/VO/RE
            else if (docStatus.Equals(DocumentEngine.STATUS_CLOSED) ||
                     docStatus.Equals(DocumentEngine.STATUS_VOIDED) ||
                     docStatus.Equals(DocumentEngine.STATUS_REVERSED))
            {
                return(action);
            }

            int  refIndex        = index;
            bool indexFromModule = true;

            GetActionFromModuleClass(AD_Table_ID, docStatus, out index, options);

            if (index == 0)
            {
                index           = refIndex;
                indexFromModule = false;
            }

            /********************
             *  Order
             */
            if (AD_Table_ID == MOrder.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED) ||
                    docStatus.Equals(DocumentEngine.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocumentEngine.STATUS_INVALID))
                {
                    options[index++] = DocumentEngine.ACTION_PREPARE;

                    //JID_0213: Close option should not be visible before doc status is completed in doc process.
                    //options[index++] = DocumentEngine.ACTION_CLOSE;

                    //	Draft Sales Order Quote/Proposal - Process
                    if (isSOTrx &&
                        ("OB".Equals(orderType) || "ON".Equals(orderType)))
                    {
                        docAction = DocumentEngine.ACTION_PREPARE;
                    }
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REACTIVATE;
                }
                else if (docStatus.Equals(DocumentEngine.STATUS_WAITINGPAYMENT))
                {
                    options[index++] = DocumentEngine.ACTION_REACTIVATE;
                    options[index++] = DocumentEngine.ACTION_CLOSE;
                }
            }

            /********************
             *  Shipment
             */
            else if (AD_Table_ID == MInOut.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Invoice
             */
            else if (AD_Table_ID == MInvoice.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Payment
             */
            else if (AD_Table_ID == MPayment.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    //options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  GL Journal
             */
            else if (AD_Table_ID == MJournal.Table_ID || AD_Table_ID == MJournalBatch.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                    //options[index++] = DocumentEngine.ACTION_REVERSE_ACCRUAL;
                }
            }

            /********************
             *  Allocation
             */
            else if (AD_Table_ID == MAllocationHdr.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Bank Statement
             */
            else if (AD_Table_ID == MBankStatement.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_VOID;
                }
            }

            /********************
             *  Inventory Movement, Physical Inventory
             */
            else if (AD_Table_ID == MMovement.Table_ID ||
                     AD_Table_ID == MInventory.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // SI_0622 : not to show VOID and REVERSE_CORRECT action on Physical Inventory
                    bool isPhysicalInventory = false;
                    if (AD_Table_ID == MInventory.Table_ID)
                    {
                        MInventory inventory = MInventory.Get(ctx, Record_ID);
                        isPhysicalInventory = !inventory.IsInternalUse();
                    }
                    if (!isPhysicalInventory)
                    {
                        //options[index++] = DocumentEngine.ACTION_VOID;
                        options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                    }
                }
            }

            // Added By Arpit
            else if (AD_Table_ID == MMovementConfirm.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // SI_0630 : System should not allow to void the Move confirmation after its completion
                    //options[index++] = DocumentEngine.ACTION_VOID;
                }
            }
            //End

            //    /********************
            //*  Warehouse Task  New Add by raghu 11 april,2011
            //*/
            //    else if (AD_Table_ID == X_M_WarehouseTask.Table_ID
            //        || AD_Table_ID == X_M_TaskList.Table_ID)
            //    {
            //        //	Draft                       ..  DR/IP/IN
            //        if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED)
            //            || docStatus.Equals(DocActionVariables.STATUS_INPROGRESS)
            //            || docStatus.Equals(DocActionVariables.STATUS_INVALID))
            //        {
            //            options[index++] = DocActionVariables.ACTION_PREPARE;
            //        }
            //        //	Complete                    ..  CO
            //        else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
            //        {
            //            options[index++] = DocActionVariables.ACTION_VOID;
            //            options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
            //        }
            //    }

            /********************
             *  Work Order New Add by raghu 11 april,2011
             */
            else if (AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WorkOrder.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INVALID))
                {
                    options[index++] = DocActionVariables.ACTION_PREPARE;
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
                {
                    //options[index++] = DocActionVariables.ACTION_VOID;
                    options[index++] = DocActionVariables.ACTION_REACTIVATE;
                }
            }

            /********************
             *  Work Order Transaction New Add by raghu 11 april,2011
             */
            else if (AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WrkOdrTransaction.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INVALID))
                {
                    options[index++] = DocActionVariables.ACTION_PREPARE;
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
                {
                    //options[index++] = DocActionVariables.ACTION_VOID;
                    options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
                }
            }

            /* Obsolete Inventory New add by Amit 24-May-2016 */
            //else if (tableName == "VA024_ObsoleteInventory")
            //{
            //    // DR/IN
            //    if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED)
            //        || docStatus.Equals(DocumentEngine.STATUS_INVALID))
            //    {
            //        options[index++] = DocumentEngine.ACTION_COMPLETE;
            //        options[index++] = DocumentEngine.ACTION_VOID;
            //    }
            //    //	Complete
            //    else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
            //    {
            //        options[index++] = DocActionVariables.ACTION_VOID;
            //        options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
            //    }
            //}

            /***For Primary thread***/
            ///**
            // *	Fill actionCombo
            // */
            //for (int i = 0; i < index; i++)
            //{
            //    //	Serach for option and add it
            //    bool added = false;
            //    for (int j = 0; j < _values.Length && !added; j++)
            //        if (options[i].Equals(_values[j]))
            //        {
            //            //actionCombo.addItem(_names[j]);
            //            vcmbAction.Items.Add(_names[j]);
            //            added = true;
            //        }
            //}

            //	setDefault
            if (docAction.Equals("--"))         //	If None, suggest closing
            {
                docAction = DocumentEngine.ACTION_CLOSE;
            }

            // check applied to display Document Actions on Transactions based on the document type
            // and the setting "Check Document Action Access" on Role window
            int    C_DocType_ID       = 0;
            int    C_DocTypeTarget_ID = 0;
            MTable table = MTable.Get(ctx, AD_Table_ID);
            PO     po    = table.GetPO(ctx, Record_ID, null);

            if (Util.GetValueOfInt(po.Get_Value("C_DocType_ID")) > 0)
            {
                C_DocType_ID = Util.GetValueOfInt(po.Get_Value("C_DocType_ID"));
            }
            if (Util.GetValueOfInt(po.Get_Value("C_DocTypeTarget_ID")) > 0)
            {
                C_DocTypeTarget_ID = Util.GetValueOfInt(po.Get_Value("C_DocTypeTarget_ID"));
                C_DocType_ID       = C_DocTypeTarget_ID;
            }

            if (C_DocType_ID > 0)
            {
                String[] docActionHolder = new String[] { docAction };
                if (po is DocOptions)
                {
                    index = ((DocOptions)po).customizeValidActions(docStatus, processing, orderType, isSOTrx ? "Y" : "N",
                                                                   AD_Table_ID, docActionHolder, options, index);
                }

                options = DocumentEngine.checkActionAccess(ctx, ctx.GetAD_Client_ID(), ctx.GetAD_Role_ID(), C_DocType_ID, options, ref index);
            }

            for (int i = 0; i < _values.Count() && defaultV.Equals(""); i++)
            {
                if (docAction.Equals(_values[i]))
                {
                    defaultV = _names[i];
                }
            }


            action.Options = options.ToList();
            if (indexFromModule)
            {
                action.Index = index + 1;
            }
            else
            {
                action.Index = index;
            }
            action.DefaultV = defaultV;

            return(action);

            /***For Primary thread***/
            //if (!defaultV.Equals(""))
            //{
            //    //vcmbAction.SelectedValue = defaultV;
            //    vcmbAction.SelectedItem = defaultV;
            //}
        }
        /// <summary>
        /// Function to update data in Master Table based on the versions saved
        /// </summary>
        /// <param name="dsRec">All Records which need to be updated</param>
        /// <param name="TableName">Version Table Name</param>
        /// <param name="VerTableID">Version Table ID</param>
        /// <returns>True/False based on the Updation of data in parent table</returns>
        private bool UpdateRecords(DataSet dsRec, string TableName, int VerTableID)
        {
            // Get Master table name from Version table
            string BaseTblName = TableName;

            if (TableName.EndsWith("_Ver"))
            {
                BaseTblName = BaseTblName.Substring(0, TableName.Length - 4);
            }
            // Master Table ID from Table name
            int BaseTableID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Table_ID FROM AD_Table WHERE TableName = '" + BaseTblName + "'"));

            // Get Column information of Master Table
            DataSet dsDBColNames = DB.ExecuteDataset("SELECT ColumnName, AD_Reference_ID, IsUpdateable, IsAlwaysUpdateable FROM AD_Column WHERE AD_Table_ID = " + BaseTableID);

            if (dsDBColNames != null && dsDBColNames.Tables[0].Rows.Count > 0)
            {
                log.Info("Processing for " + TableName + " :: ");

                StringBuilder sqlSB           = new StringBuilder("");
                bool          recordProcessed = false;
                // create object of Master Table
                MTable tbl = new MTable(GetCtx(), BaseTableID, null);
                // create object of Version table
                MTable tblVer = new MTable(GetCtx(), VerTableID, null);

                // check whether master table has Single key
                bool isSingleKey = tbl.IsSingleKey();

                // List of records which were not processed by process in case of any error
                List <string> keys  = new List <string>();
                StringBuilder sbKey = new StringBuilder("");
                // Loop through the records which need to be updated on Master Table
                for (int i = 0; i < dsRec.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = dsRec.Tables[0].Rows[i];
                    sbKey.Clear();
                    PO poDest   = null;
                    PO poSource = tblVer.GetPO(GetCtx(), dr, null);
                    // if table has single key
                    if (isSingleKey)
                    {
                        // Create object of PO Class from TableName and Record ID
                        poDest = MTable.GetPO(GetCtx(), BaseTblName, Util.GetValueOfInt(dr[BaseTblName + "_ID"]), null);
                        sbKey.Append(Util.GetValueOfInt(dr[BaseTblName + "_ID"]));
                    }
                    else
                    {
                        // Create object of PO Class from combination of key columns
                        string[]      keyCols   = tbl.GetKeyColumns();
                        StringBuilder whereCond = new StringBuilder("");
                        for (int w = 0; w < keyCols.Length; w++)
                        {
                            if (w == 0)
                            {
                                if (keyCols[w] != null)
                                {
                                    whereCond.Append(keyCols[w] + " = " + poSource.Get_Value(keyCols[w]));
                                }
                                else
                                {
                                    whereCond.Append(" NVL(" + keyCols[w] + ",0) = 0");
                                }
                            }
                            else
                            {
                                if (keyCols[w] != null)
                                {
                                    whereCond.Append(" AND " + keyCols[w] + " = " + poSource.Get_Value(keyCols[w]));
                                }
                                else
                                {
                                    whereCond.Append(" AND NVL(" + keyCols[w] + ",0) = 0");
                                }
                            }
                        }
                        poDest = tbl.GetPO(GetCtx(), whereCond.ToString(), null);
                        sbKey.Append(whereCond);
                    }

                    // check if there is any error in processing record, then continue and do not process next versions
                    if (keys.Contains(sbKey.ToString()))
                    {
                        continue;
                    }

                    // Check whether Master Table contains "Processing" Column
                    if (poDest.Get_ColumnIndex("Processing") >= 0)
                    {
                        // if "Processing" column found then return, do not update in Master Table,
                        // because transaction might be in approval process
                        if (Util.GetValueOfString(poSource.Get_Value("Processing")) == "Y")
                        {
                            keys.Add(sbKey.ToString());
                            continue;
                        }
                    }

                    // Check whether Master Table contains "Processed" Column
                    if (poDest.Get_ColumnIndex("Processed") >= 0)
                    {
                        if (Util.GetValueOfString(poSource.Get_Value("Processed")) == "Y")
                        {
                            recordProcessed = true;
                        }
                    }

                    // set client and Organization ID from Version table to Master
                    // as copy PO set these ID's as 0
                    poDest.SetAD_Client_ID(poSource.GetAD_Client_ID());
                    poDest.SetAD_Org_ID(poSource.GetAD_Org_ID());

                    StringBuilder sbColName = new StringBuilder("");
                    // Loop through all the columns in Master Table
                    for (int j = 0; j < dsDBColNames.Tables[0].Rows.Count; j++)
                    {
                        sbColName.Clear();
                        // Get Name of Column
                        sbColName.Append(dsDBColNames.Tables[0].Rows[j]["ColumnName"]);

                        // check if column exist in Default columns list, in that case do not update and continue to next column
                        if (defcolNames.Contains(sbColName.ToString()))
                        {
                            continue;
                        }
                        // No need to update Primary key column, continue to next column
                        if (sbColName.ToString().Equals(BaseTblName + "_ID"))
                        {
                            continue;
                        }
                        // if column is of "Yes-No" type i.e. Reference ID is 20 (Fixed) then set True/False
                        if (Util.GetValueOfInt(dsDBColNames.Tables[0].Rows[j]["AD_Reference_ID"]) == 20)
                        {
                            Object val = false;
                            if (poSource.Get_Value(sbColName.ToString()) != null)
                            {
                                val = poSource.Get_Value(sbColName.ToString());
                            }
                            poDest.Set_Value(sbColName.ToString(), val);
                        }
                        else
                        {
                            poDest.Set_ValueNoCheck(sbColName.ToString(), poSource.Get_Value(sbColName.ToString()));
                        }

                        // Check if Master record is Processed and Always Updatable is false then check whether any value updated in such column
                        // if value updated then return false, can't change data in Processed record if it's not Always Updatable
                        if (recordProcessed && Util.GetValueOfString(dsDBColNames.Tables[0].Rows[j]["IsAlwaysUpdateable"]) == "N")
                        {
                            bool upd = poDest.Is_ValueChanged(sbColName.ToString());
                            if (upd)
                            {
                                msg.Append("Can't update  " + sbColName.ToString() + " in " + TableName);
                                log.SaveError("ERROR", "Can not update processed record for column ==>> " + sbColName.ToString());
                                // Add record to the list of unprocessed records
                                keys.Add(sbKey.ToString());
                                continue;
                            }
                        }
                    }

                    // Save Master Record
                    if (!poDest.Save())
                    {
                        // Add record to the list of unprocessed records
                        keys.Add(sbKey.ToString());
                        // Check for Errors
                        ValueNamePair vnp   = VLogger.RetrieveError();
                        string        error = "";
                        if (vnp != null)
                        {
                            error = vnp.GetName();
                            if (error == "" && vnp.GetValue() != null)
                            {
                                error = vnp.GetValue();
                            }
                        }
                        if (error == "")
                        {
                            error = "Error in updating Version";
                        }

                        msg.Append("Save error in " + TableName + " ==>> " + error);
                        log.SaveError("ERROR", error);

                        sqlSB.Clear();

                        sqlSB.Append("UPDATE " + TableName + " SET VersionLog = '" + error + "' WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]);
                        int count = DB.ExecuteQuery(sqlSB.ToString(), null, null);

                        continue;
                    }
                    else
                    {
                        // Update Version table, Set "ProcessedVersion" to "Y", so that it don't consider when process runs next time
                        sqlSB.Clear();
                        // Update against record id in case of Single key, and update Key column in version table as well in case of new record
                        if (isSingleKey)
                        {
                            sqlSB.Append("UPDATE " + TableName + " SET ProcessedVersion = 'Y', " + BaseTblName + "_ID  = " + poDest.Get_ID() + " WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]);
                        }
                        // else
                        else
                        {
                            sqlSB.Append("UPDATE " + TableName + " SET ProcessedVersion = 'Y' WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]);
                        }

                        int count = DB.ExecuteQuery(sqlSB.ToString(), null, null);
                        if (count <= 0)
                        {
                            log.Info(TableName + " not updated ==>> " + sqlSB.ToString());
                        }
                    }
                }
            }
            return(true);
        }
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override bool BeforeSave(bool newRecord)
        {
            if (Is_ValueChanged("DueAmt"))
            {
                log.Fine("beforeSave");
                SetIsValid(false);
            }
            oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt"));

            if (Env.IsModuleInstalled("VA009_"))
            {
                // get invoice currency for rounding
                MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID());
                SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision()));
                SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision()));
                // when invoice schedule have payment reference then need to check payment mode on payment window & update here
                if (GetC_Payment_ID() > 0)
                {
                    #region for payment
                    MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx());
                    SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID());

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

            return(true);
        }