}   //  sendAlert

        private bool Escalate(MRequest request)
        {
            //  Get Supervisor
            MUser supervisor    = request.GetSalesRep(); //	self
            int   supervisor_ID = request.GetSalesRep().GetSupervisor_ID();

            if ((supervisor_ID == 0) && (m_model.GetSupervisor_ID() != 0))
            {
                supervisor_ID = m_model.GetSupervisor_ID();
            }
            if ((supervisor_ID != 0) && (supervisor_ID != request.GetAD_User_ID()))
            {
                supervisor = MUser.Get(GetCtx(), supervisor_ID);
            }

            //  Escalated: Request {0} to {1}
            String subject = Msg.GetMsg(m_client.GetAD_Language(), "RequestEscalate",
                                        new String[] { request.GetDocumentNo(), supervisor.GetName() });
            String to = request.GetSalesRep().GetEMail();

            if ((to == null) || (to.Length == 0))
            {
                log.Warning("SalesRep has no EMail - " + request.GetSalesRep());
            }
            else
            {
                m_client.SendEMail(request.GetSalesRep_ID(), subject, request.GetSummary(), request.CreatePDF());
            }

            //	Not the same - send mail to supervisor
            if (request.GetSalesRep_ID() != supervisor.GetAD_User_ID())
            {
                to = supervisor.GetEMail();
                if ((to == null) || (to.Length == 0))
                {
                    log.Warning("Supervisor has no EMail - " + supervisor);
                }
                else
                {
                    m_client.SendEMail(supervisor.GetAD_User_ID(), subject, request.GetSummary(), request.CreatePDF());
                }
            }

            //  ----------------
            request.SetDueType();
            request.SetIsEscalated(true);
            request.SetResult(subject);
            return(request.Save());
        }   //  escalate
Beispiel #2
0
        /// <summary>
        /// Save New User and organization accesses provided to it.
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Email"></param>
        /// <param name="Value"></param>
        /// <param name="password"></param>
        /// <param name="mobile"></param>
        /// <param name="OrgID"></param>
        /// <returns></returns>
        public String SaveNewUser(string Name, string Email, string Value, string password, string mobile, List <int> OrgID)
        {
            string msg;
            string info = "";
            MUser  user = new MUser(ctx, 0, null);

            user.SetName(Name);
            user.SetIsLoginUser(true);
            user.SetEMail(Email);

            if (!string.IsNullOrEmpty(password))
            {
                string key = ctx.GetSecureKey();
                password = SecureEngineBridge.DecryptByClientKey(password, key);
                user.SetPassword(password);
            }

            if (!String.IsNullOrEmpty(mobile))
            {
                user.SetMobile(mobile);
            }

            if (!string.IsNullOrEmpty(Value))
            {
                user.SetValue(Value);
            }
            if (user.Save())
            {
                if (OrgID != null)
                {
                    for (int i = 0; i < OrgID.Count; i++)
                    {
                        MOrg           org   = new MOrg(ctx, OrgID[i], null);
                        MUserOrgAccess roles = new MUserOrgAccess(org, user.GetAD_User_ID());
                        roles.SetAD_Client_ID(ctx.GetAD_Client_ID());
                        roles.SetAD_Org_ID(OrgID[i]);
                        roles.SetIsReadOnly(false);
                        roles.Save();
                    }
                }
            }
            else
            {
                ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError();

                if (ppE != null)
                {
                    msg  = ppE.GetValue();
                    info = ppE.GetName();
                }
            }



            return(info);
        }
Beispiel #3
0
        /// <summary>
        /// Save New User and organization accesses provided to it.
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Email"></param>
        /// <param name="Value"></param>
        /// <param name="password"></param>
        /// <param name="mobile"></param>
        /// <param name="OrgID"></param>
        /// <returns></returns>
        public bool SaveNewUser(string Name, string Email, string Value, string password, string mobile, List <int> OrgID)
        {
            bool  retValue = false;
            MUser user     = new MUser(ctx, 0, null);

            user.SetName(Name);
            user.SetIsLoginUser(true);
            user.SetEMail(Email);

            if (!string.IsNullOrEmpty(password))
            {
                string key = ctx.GetSecureKey();
                password = SecureEngineBridge.DecryptByClientKey(password, key);
                user.SetPassword(password);
            }

            if (!String.IsNullOrEmpty(mobile))
            {
                user.SetMobile(mobile);
            }

            if (!string.IsNullOrEmpty(Value))
            {
                user.SetValue(Value);
            }
            if (user.Save())
            {
                if (OrgID != null)
                {
                    for (int i = 0; i < OrgID.Count; i++)
                    {
                        MOrg           org   = new MOrg(ctx, OrgID[i], null);
                        MUserOrgAccess roles = new MUserOrgAccess(org, user.GetAD_User_ID());
                        roles.SetAD_Client_ID(ctx.GetAD_Client_ID());
                        roles.SetAD_Org_ID(OrgID[i]);
                        roles.SetIsReadOnly(false);
                        roles.Save();
                    }
                }

                retValue = true;
            }
            return(retValue);
        }
Beispiel #4
0
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns> Message</returns>
        protected override String DoIt()
        {
            log.Info("R_MailText_ID=" + _R_MailText_ID);
            //	Mail Test
            _MailText = new MMailText(GetCtx(), _R_MailText_ID, Get_TrxName());
            if (_MailText.GetR_MailText_ID() == 0)
            {
                throw new Exception("Not found @R_MailText_ID@=" + _R_MailText_ID);
            }
            //	Client Info
            _client = MClient.Get(GetCtx());
            if (_client.GetAD_Client_ID() == 0)
            {
                throw new Exception("Not found @AD_Client_ID@");
            }
            if (_client.GetSmtpHost() == null || _client.GetSmtpHost().Length == 0)
            {
                throw new Exception("No SMTP Host found");
            }
            //
            if (_AD_User_ID > 0)
            {
                _from = new MUser(GetCtx(), _AD_User_ID, Get_TrxName());
                if (_from.GetAD_User_ID() == 0)
                {
                    throw new Exception("No found @AD_User_ID@=" + _AD_User_ID);
                }
            }
            log.Fine("From " + _from);
            //long start = System.currentTimeMillis();
            long start = CommonFunctions.CurrentTimeMillis();

            if (_R_InterestArea_ID > 0)
            {
                SendInterestArea();
            }
            if (_C_BP_Group_ID > 0)
            {
                SendBPGroup();
            }
            return("@Created@=" + _counter + ", @Errors@=" + _errors + " - "
                   + (CommonFunctions.CurrentTimeMillis() - start) + "ms");
        }       //	doIt
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Name.Value))
            {
                return;
            }
            HttpRequest q    = Request;
            string      lang = q.QueryString["lang"];

            usernotSaved    = Msg.GetMsg(lang, "VIS_ErrorSavingUser");
            Button1.Enabled = false;
            int AD_Client_ID = 0;
            int AD_Org_ID    = 0;

            int     inviteID = Convert.ToInt32(SecureEngine.Decrypt(q.QueryString["inviteID"]));
            String  sql      = "SELECT * FROM AD_InviteUser WHERE AD_InviteUser_ID=" + inviteID;
            DataSet dsIUser  = DB.ExecuteDataset(sql);

            if (dsIUser != null && dsIUser.Tables[0].Rows.Count > 0)
            {
                AD_Org_ID    = Convert.ToInt32(dsIUser.Tables[0].Rows[0]["AD_Org_ID"]);
                AD_Client_ID = Convert.ToInt32(dsIUser.Tables[0].Rows[0]["AD_Client_ID"]);
            }

            sql = "SELECT AD_Role_ID FROM ad_inviteuser_role WHERE AD_InviteUser_ID= " + inviteID;
            DataSet ds = DB.ExecuteDataset(sql);



            Ctx ctx = new Ctx();

            ctx.SetAD_Client_ID(AD_Client_ID);
            ctx.SetAD_Org_ID(AD_Org_ID);


            MUser user = new MUser(ctx, 0, null);

            user.SetAD_Client_ID(AD_Client_ID);
            user.SetAD_Org_ID(AD_Org_ID);
            user.SetIsLoginUser(true);
            user.SetName(Name.Value);
            user.SetValue(userIDs.Value);
            user.SetEMail(email.Value);
            user.SetPassword(passwords.Value);
            user.SetMobile(mobile.Value);
            if (user.Save())
            {
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        MUserRoles uRoles = new MUserRoles(ctx, user.GetAD_User_ID(), Convert.ToInt32(ds.Tables[0].Rows[i]["AD_Role_ID"]), null);
                        uRoles.SetAD_Client_ID(AD_Client_ID);
                        uRoles.SetAD_Org_ID(AD_Org_ID);
                        uRoles.Save();
                    }
                }

                sendMail.Visible = true;
                Name.Value       = "";
                userIDs.Value    = "";
                email.Value      = "";
                passwords.Value  = "";
                mobile.Value     = "";
            }
            else
            {
                Button1.Enabled    = true;
                sendMail.InnerText = usernotSaved;
                sendMail.Visible   = true;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Send notice to users.
        /// </summary>
        /// <param name="list"> List of columns changed.</param>
        protected void SendNotices(List <String> list)
        {
            bool          isEmailSent = false;
            StringBuilder finalMsg    = new StringBuilder();

            finalMsg.Append(Msg.Translate(GetCtx(), "R_Request_ID") + ": " + _req.GetDocumentNo()).Append("\n").Append(Msg.Translate(GetCtx(), "R_NotificSent"));
            //	Subject
            if (mailText_ID == 0)
            {
                subject = Msg.Translate(GetCtx(), "R_Request_ID")
                          + " " + Msg.GetMsg(GetCtx(), "Updated", true) + ": " + _req.GetDocumentNo() + " (●" + MTable.Get_Table_ID(Table_Name) + "-" + _req.GetR_Request_ID() + "●) " + Msg.GetMsg(GetCtx(), "DoNotChange");
            }
            //	Message

            //		UpdatedBy: Joe
            int   UpdatedBy = GetCtx().GetAD_User_ID();
            MUser from      = MUser.Get(GetCtx(), UpdatedBy);

            FileInfo pdf = CreatePDF();

            log.Finer(message.ToString());

            //	Prepare sending Notice/Mail
            MClient client = MClient.Get(GetCtx(), GetAD_Client_ID());

            //	ReSet from if external
            if (from.GetEMailUser() == null || from.GetEMailUserPW() == null)
            {
                from = null;
            }
            _success = 0;
            _failure = 0;
            _notices = 0;

            /** List of users - aviod duplicates	*/
            List <int> userList = new List <int>();
            String     sql      = "SELECT u.AD_User_ID, u.NotificationType, u.EMail, u.Name, MAX(r.AD_Role_ID) "
                                  + "FROM RV_RequestUpdates_Only ru"
                                  + " INNER JOIN AD_User u ON (ru.AD_User_ID=u.AD_User_ID)"
                                  + " LEFT OUTER JOIN AD_User_Roles r ON (u.AD_User_ID=r.AD_User_ID) "
                                  + "WHERE ru.R_Request_ID= " + _req.GetR_Request_ID()
                                  + " GROUP BY u.AD_User_ID, u.NotificationType, u.EMail, u.Name";

            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, null);
                while (idr.Read())
                {
                    int    AD_User_ID       = Utility.Util.GetValueOfInt(idr[0]);
                    String NotificationType = Util.GetValueOfString(idr[1]); //idr.GetString(1);
                    if (NotificationType == null)
                    {
                        NotificationType = X_AD_User.NOTIFICATIONTYPE_EMail;
                    }
                    String email = Util.GetValueOfString(idr[2]);// idr.GetString(2);

                    if (String.IsNullOrEmpty(email))
                    {
                        continue;
                    }

                    String Name = Util.GetValueOfString(idr[3]);//idr.GetString(3);
                    //	Role
                    int AD_Role_ID = Utility.Util.GetValueOfInt(idr[4]);
                    if (idr == null)
                    {
                        AD_Role_ID = -1;
                    }

                    //	Don't send mail to oneself
                    //		if (AD_User_ID == UpdatedBy)
                    //			continue;

                    //	No confidential to externals
                    if (AD_Role_ID == -1 &&
                        (_req.GetConfidentialTypeEntry().Equals(X_R_Request.CONFIDENTIALTYPE_Internal) ||
                         _req.GetConfidentialTypeEntry().Equals(X_R_Request.CONFIDENTIALTYPE_PrivateInformation)))
                    {
                        continue;
                    }

                    if (X_AD_User.NOTIFICATIONTYPE_None.Equals(NotificationType))
                    {
                        log.Config("Opt out: " + Name);
                        continue;
                    }
                    if ((X_AD_User.NOTIFICATIONTYPE_EMail.Equals(NotificationType) ||
                         X_AD_User.NOTIFICATIONTYPE_EMailPlusNotice.Equals(NotificationType)) &&
                        (email == null || email.Length == 0))
                    {
                        if (AD_Role_ID >= 0)
                        {
                            NotificationType = X_AD_User.NOTIFICATIONTYPE_Notice;
                        }
                        else
                        {
                            log.Config("No EMail: " + Name);
                            continue;
                        }
                    }
                    if (X_AD_User.NOTIFICATIONTYPE_Notice.Equals(NotificationType) &&
                        AD_Role_ID >= 0)
                    {
                        log.Config("No internal User: "******"\n").Append(user.GetName()).Append(".");
                    isEmailSent = true;
                }

                idr.Close();
                // Notification For Role
                List <int> _users = SendRoleNotice();
                for (int i = 0; i < _users.Count; i++)
                {
                    MUser  user             = new MUser(GetCtx(), _users[i], null);
                    int    AD_User_ID       = user.GetAD_User_ID();
                    String NotificationType = user.GetNotificationType(); //idr.GetString(1);
                    if (NotificationType == null)
                    {
                        NotificationType = X_AD_User.NOTIFICATIONTYPE_EMail;
                    }
                    String email = user.GetEMail();// idr.GetString(2);

                    if (String.IsNullOrEmpty(email))
                    {
                        continue;
                    }

                    String Name = user.GetName(); //idr.GetString(3);
                                                  //	Role

                    if (X_AD_User.NOTIFICATIONTYPE_None.Equals(NotificationType))
                    {
                        log.Config("Opt out: " + Name);
                        continue;
                    }

                    //
                    SendNoticeNow(_users[i], NotificationType,
                                  client, from, subject, message.ToString(), pdf);
                    finalMsg.Append("\n").Append(user.GetName()).Append(".");
                    isEmailSent = true;
                }

                if (!isEmailSent)
                {
                    finalMsg.Clear();
                    finalMsg.Append(Msg.Translate(GetCtx(), "R_Request_ID") + ": " + _req.GetDocumentNo()).Append("\n").Append(Msg.Translate(GetCtx(), "R_NoNotificationSent"));
                }

                int   AD_Message_ID = 834;
                MNote note          = new MNote(GetCtx(), AD_Message_ID, GetCtx().GetAD_User_ID(),
                                                X_R_Request.Table_ID, _req.GetR_Request_ID(),
                                                subject, finalMsg.ToString(), Get_TrxName());
                if (note.Save())
                {
                    log.Log(Level.INFO, "ProcessFinished", "");
                }
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }


            //	New Sales Rep (may happen if sent from beforeSave
            if (!userList.Contains(_req.GetSalesRep_ID()))
            {
                SendNoticeNow(_req.GetSalesRep_ID(), null,
                              client, from, subject, message.ToString(), pdf);
            }
        }
        /**
         *  Create Trial Asset
         *	@param ctx context
         *	@param user user
         *	@param entityType entity type
         *	@return asset or null if no product found
         */
        public static MAsset GetTrial(Ctx ctx, MUser user, String entityType)
        {
            if (user == null)
            {
                _log.Warning("Cannot create Trial - No User");
                return(null);
            }
            if (Util.IsEmpty(entityType))
            {
                _log.Warning("Cannot create Trial - No Entity Type");
                return(null);
            }
            MProduct product = MProduct.GetTrial(ctx, entityType);

            if (product == null)
            {
                _log.Warning("No Trial for Entity Type=" + entityType);
                return(null);
            }
            //
            DateTime now = Convert.ToDateTime(CommonFunctions.CurrentTimeMillis());
            //
            MAsset asset = new MAsset(ctx, 0, null);

            asset.SetClientOrg(user);
            asset.SetAssetServiceDate(now);
            asset.SetIsOwned(false);
            asset.SetIsTrialPhase(true);
            //
            MBPartner partner    = new MBPartner(ctx, user.GetC_BPartner_ID(), null);
            String    documentNo = "Trial";
            //	Value
            String value = partner.GetValue() + "_" + product.GetValue();

            if (value.Length > 40 - documentNo.Length)
            {
                value = value.Substring(0, 40 - documentNo.Length) + documentNo;
            }
            asset.SetValue(value);
            //	Name		MProduct.afterSave
            String name = "Trial " + partner.GetName() + " - " + product.GetName();

            if (name.Length > 60)
            {
                name = name.Substring(0, 60);
            }
            asset.SetName(name);
            //	Description
            String description = product.GetDescription();

            asset.SetDescription(description);

            //	User
            asset.SetAD_User_ID(user.GetAD_User_ID());
            asset.SetC_BPartner_ID(user.GetC_BPartner_ID());
            //	Product
            asset.SetM_Product_ID(product.GetM_Product_ID());
            asset.SetA_Asset_Group_ID(product.GetA_Asset_Group_ID());
            asset.SetQty(new Decimal(product.GetSupportUnits()));
            //	Guarantee & Version
            asset.SetGuaranteeDate(TimeUtil.AddDays(now, product.GetTrialPhaseDays()));
            asset.SetVersionNo(product.GetVersionNo());
            //
            return(asset);
        }
Beispiel #8
0
        /// <summary>
        /// Add Or Update Business Partner
        /// </summary>
        /// <param name="searchKey"></param>
        /// <param name="name"></param>
        /// <param name="name2"></param>
        /// <param name="greeting"></param>
        /// <param name="bpGroup"></param>
        /// <param name="bpRelation"></param>
        /// <param name="bpLocation"></param>
        /// <param name="contact"></param>
        /// <param name="greeting1"></param>
        /// <param name="title"></param>
        /// <param name="email"></param>
        /// <param name="address"></param>
        /// <param name="phoneNo"></param>
        /// <param name="phoneNo2"></param>
        /// <param name="fax"></param>
        /// <param name="ctx"></param>
        /// <param name="_windowNo"></param>
        /// <param name="BPtype"></param>
        /// <param name="C_BPartner_ID"></param>
        /// <returns></returns>

        public string AddBPartner(string searchKey, string name, string name2, string greeting, string bpGroup, string bpRelation, string bpLocation, string contact, string greeting1, string title, string email, string address, string phoneNo, string phoneNo2, string fax, Ctx ctx, int _windowNo, string BPtype, int C_BPartner_ID, bool isCustomer, bool isVendor, bool isProspect, string fileUrl, string umobile, string webUrl, bool isEmployee)
        {
            StringBuilder strError     = new StringBuilder();
            int           AD_Client_ID = ctx.GetAD_Client_ID();

            if (C_BPartner_ID > 0)
            {
                _partner = new MBPartner(ctx, C_BPartner_ID, null);
            }
            else
            {
                _partner = MBPartner.GetTemplate(ctx, AD_Client_ID);
            }
            bool isSOTrx = ctx.IsSOTrx(_windowNo);

            _partner.SetIsCustomer(isSOTrx);
            _partner.SetIsVendor(!isSOTrx);
            // JID_1197 IN Business partner  updating Createdby,Updatedby,Created,Updated fields as per changed date
            _partner.Set_ValueNoCheck("CreatedBy", ctx.GetAD_User_ID());
            _partner.Set_ValueNoCheck("Created", DateTime.Now);
            _partner.Set_ValueNoCheck("Updated", DateTime.Now);
            _partner.Set_ValueNoCheck("UpdatedBy", ctx.GetAD_User_ID());
            if (BPtype != null && (!isCustomer && !isVendor))
            {
                if (BPtype.Contains("Customer"))
                {
                    _partner.SetIsCustomer(true);
                }
                if (BPtype.Contains("Employee"))
                {
                    _partner.SetIsEmployee(true);
                }
                if (BPtype.Contains("Vendor"))
                {
                    _partner.SetIsVendor(true);
                }
                if (BPtype.Contains("Prospect"))
                {
                    _partner.SetIsProspect(true);
                }

                /*
                 * if (BPtype == "Customer")
                 * {
                 *  _partner.SetIsCustomer(true);
                 * }
                 * else if (BPtype == "Employee")
                 * {
                 *  _partner.SetIsEmployee(true);
                 * }
                 * else if (BPtype == "Vendor")
                 * {
                 *  _partner.SetIsVendor(true);
                 * }
                 * else if (BPtype == "Prospect")
                 * {
                 *  _partner.SetIsProspect(true);
                 * }*/
            }
            if (isCustomer)
            {
                _partner.SetIsCustomer(true);
            }
            else
            {
                _partner.SetIsCustomer(false);
            }
            if (isVendor)
            {
                _partner.SetIsVendor(true);
            }
            else
            {
                _partner.SetIsVendor(false);
            }
            if (isProspect)
            {
                _partner.SetIsProspect(true);
            }
            else
            {
                _partner.SetIsProspect(false);
            }

            if (isEmployee)
            {
                _partner.SetIsEmployee(true);
            }
            else
            {
                _partner.SetIsEmployee(false);
            }

            if (searchKey == null || searchKey.Length == 0)
            {
                //	get Table Documet No
                searchKey = MSequence.GetDocumentNo(ctx.GetAD_Client_ID(), "C_BPartner", null, ctx);
                //Dispatcher.BeginInvoke(() => { txtValue.Text = value; });
            }
            _partner.SetValue(searchKey);
            //
            _partner.SetName(name);
            _partner.SetURL(webUrl);
            //  _partner.SetName2(name2);
            //KeyNamePair p = (KeyNamePair)cmbGreetingBP.SelectedItem;
            //if (greeting >0)
            //{
            //    _partner.SetC_Greeting_ID(greeting);
            //}
            //else
            //{
            //    _partner.SetC_Greeting_ID(0);
            //}
            if (greeting != string.Empty)
            {
                _partner.SetC_Greeting_ID(Convert.ToInt32(greeting));
            }
            else
            {
                _partner.SetC_Greeting_ID(0);
            }
            /***************************************************/
            _partner.SetC_BP_Group_ID(Util.GetValueOfInt(bpGroup));
            /***************************************************/

            if (_partner.Save())
            {
                log.Fine("C_BPartner_ID=" + _partner.GetC_BPartner_ID());
            }
            else
            {
                // Classes.ShowMessage.Error("SearchKeyExist", null);
                strError.Append("SearchKeyExist");
                //this.Cursor = Cursors.Arrow;
                return(strError.ToString());
            }

            //	***** Business Partner - Location *****
            if (_pLocation == null)
            {
                if (C_BPartner_ID > 0)
                {
                    _pLocation = new MBPartnerLocation(ctx, GetBPartnerLocationID(_partner.Get_ID()), null);
                    if (_pLocation.Get_ID() <= 0)
                    {
                        _pLocation = new MBPartnerLocation(_partner);
                    }
                }
                else
                {
                    _pLocation = new MBPartnerLocation(_partner);
                }
            }
            if (address != string.Empty)
            {
                _pLocation.SetC_Location_ID(Convert.ToInt32(address));
            }

            //
            _pLocation.SetPhone(phoneNo);
            // _pLocation.SetPhone2(phoneNo2);
            _pLocation.SetFax(fax);
            if (_pLocation.Save())
            {
                log.Fine("C_BPartner_Location_ID=" + _pLocation.GetC_BPartner_Location_ID());
            }
            else
            {
                //   ADialog.error(m_WindowNo, this, "BPartnerNotSaved", Msg.translate(Env.getCtx(), "C_BPartner_Location_ID"));
                // Classes.ShowMessage.Error("BPartnerNotSaved", null);
                //this.Cursor = Cursors.Arrow;
                strError.Append("BPartnerNotSaved");
                return(strError.ToString());
            }

            //	***** Business Partner - User *****
            //String contact = txtContact.Text;
            //String email = txtEMail.Text;
            if (_user == null && (contact.Length > 0 || email.Length > 0))
            {
                if (C_BPartner_ID > 0)
                {
                    _user = new MUser(ctx, GetUserID(_partner.Get_ID()), null);
                }
                else
                {
                    _user = new MUser(_partner);
                }
            }
            if (_user != null)
            {
                if (contact.Length == 0)
                {
                    contact = name;
                }
                _user.SetName(contact);
                _user.SetEMail(email);
                _user.SetTitle(title);
                _user.SetC_Location_ID(Convert.ToInt32(address));

                // = (KeyNamePair)cmbGreetingC.SelectedItem;

                //if (greeting1 >0)
                //    _user.SetC_Greeting_ID(greeting1);
                if (greeting1 != string.Empty)
                {
                    _user.SetC_Greeting_ID(Convert.ToInt32(greeting1));
                }
                else
                {
                    _user.SetC_Greeting_ID(0);
                }
                //
                _user.SetPhone(phoneNo);
                // _user.SetPhone2(phoneNo2);
                _user.SetMobile(umobile);
                _user.SetFax(fax);
                _user.SetC_BPartner_Location_ID(_pLocation.GetC_BPartner_Location_ID());
                if (_user.Save())
                {
                    if (fileUrl != null && fileUrl != string.Empty)
                    {
                        _user.SetAD_Image_ID(SaveUserImage(ctx, fileUrl, _user.GetAD_User_ID()));
                    }
                    if (_user.Save())
                    {
                        log.Fine("AD_User_ID(AD_Image_ID)=" + _user.GetAD_User_ID() + "(" + _user.GetAD_Image_ID() + ")");
                    }
                    log.Fine("AD_User_ID=" + _user.GetAD_User_ID());
                }
                else
                {
                    //Classes.ShowMessage.Error("BPartnerNotSaved", null);
                    //this.Cursor = Cursors.Arrow;
                    strError.Append("BPartnerNotSaved");
                    return(strError.ToString());
                }

                /*************************************************/
                if ((bpRelation != null && bpLocation != null) && (bpRelation != string.Empty && bpLocation != string.Empty))
                {
                    if (bpRelation.ToString().Trim() == "" || bpLocation.ToString().Trim() == "")
                    {
                        int dele = DB.ExecuteQuery("DELETE from C_BP_Relation where c_bpartner_id=" + _partner.GetC_BPartner_ID(), null, null);
                        if (dele == -1)
                        {
                            log.SaveError("C_BP_RelationNotDeleted", "c_bpartner_id=" + _partner.GetC_BPartner_ID());
                        }
                    }
                    else
                    {
                        //Business Partner Relation
                        if (C_BPartner_ID > 0)
                        {
                            _bprelation = new X_C_BP_Relation(ctx, GetBPRelationID(_partner.Get_ID()), null);
                        }
                        else
                        {
                            _bprelation = new X_C_BP_Relation(ctx, 0, null);
                        }
                        _bprelation.SetAD_Client_ID(_partner.GetAD_Client_ID());
                        _bprelation.SetAD_Org_ID(_partner.GetAD_Org_ID());
                        _bprelation.SetName(_partner.GetName());
                        _bprelation.SetDescription(_partner.GetDescription());
                        _bprelation.SetC_BPartner_ID(_partner.GetC_BPartner_ID());
                        _bprelation.SetC_BPartner_Location_ID(_pLocation.GetC_BPartner_Location_ID());
                        _bprelation.SetC_BP_Relation_ID(Util.GetValueOfInt(bpRelation));
                        _bprelation.SetC_BPartnerRelation_ID(Util.GetValueOfInt(bpRelation));
                        _bprelation.SetC_BPartnerRelation_Location_ID(Util.GetValueOfInt(bpLocation));
                        _bprelation.SetIsBillTo(true);
                        if (_bprelation.Save())
                        {
                            log.Fine("C_BP_Relation_ID=" + _bprelation.GetC_BP_Relation_ID());
                        }
                        else
                        {
                            //Classes.ShowMessage.Error("BPRelationNotSaved", null);

                            //this.Cursor = Cursors.Arrow;
                            strError.Append("BPRelationNotSaved");
                            return(strError.ToString());
                        }
                    }
                }
                /*************************************************/
            }
            return(strError.ToString());
        }
Beispiel #9
0
        }                                  //	prepare

        /// <summary>
        /// Perrform Process.
        /// </summary>
        /// <returns>clear message</returns>
        protected override String DoIt()
        {
            StringBuilder sql         = null;
            int           no          = 0;
            String        clientCheck = " AND AD_Client_ID=" + _AD_Client_ID;

            //	****	Prepare	****

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

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

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

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

            //	Document Type - PO - SO
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT C_DocType_ID FROM C_DocType d WHERE d.Name=o.DocTypeName"
                                    + " AND d.DocBaseType IN ('API','APC') AND o.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND IsSOTrx='N' AND DocTypeName IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set PO DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT C_DocType_ID FROM C_DocType d WHERE d.Name=o.DocTypeName"
                                    + " AND d.DocBaseType IN ('ARI','ARC') AND o.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND IsSOTrx='Y' AND DocTypeName IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set SO DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT C_DocType_ID FROM C_DocType d WHERE d.Name=o.DocTypeName"
                                    + " AND d.DocBaseType IN ('API','ARI','APC','ARC') AND o.AD_Client_ID=d.AD_Client_ID) "
                                    //+ "WHERE C_DocType_ID IS NULL AND IsSOTrx IS NULL AND DocTypeName IS NOT NULL AND I_IsImported<>'Y'").Append (clientCheck);
                                    + "WHERE C_DocType_ID IS NULL AND DocTypeName IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid DocTypeName, ' "
                                    + "WHERE C_DocType_ID IS NULL AND DocTypeName IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid DocTypeName=" + no);
            }
            //	DocType Default
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT MAX(C_DocType_ID) FROM C_DocType d WHERE d.IsDefault='Y'"
                                    + " AND d.DocBaseType='API' AND o.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND IsSOTrx='N' AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set PO Default DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT MAX(C_DocType_ID) FROM C_DocType d WHERE d.IsDefault='Y'"
                                    + " AND d.DocBaseType='ARI' AND o.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND IsSOTrx='Y' AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set SO Default DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_DocType_ID=(SELECT MAX(C_DocType_ID) FROM C_DocType d WHERE d.IsDefault='Y'"
                                    + " AND d.DocBaseType IN('ARI','API') AND o.AD_Client_ID=d.AD_Client_ID) "
                                    + "WHERE C_DocType_ID IS NULL AND IsSOTrx IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Fine("Set Default DocType=" + no);
            }
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No DocType, ' "
                                    + "WHERE C_DocType_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No DocType=" + no);
            }

            //	Set IsSOTrx
            sql = new StringBuilder("UPDATE I_Invoice o SET IsSOTrx='Y' "
                                    + "WHERE EXISTS (SELECT * FROM C_DocType d WHERE o.C_DocType_ID=d.C_DocType_ID AND d.DocBaseType='ARI' AND o.AD_Client_ID=d.AD_Client_ID)"
                                    + " AND C_DocType_ID IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set IsSOTrx=Y=" + no);
            sql = new StringBuilder("UPDATE I_Invoice o SET IsSOTrx='N' "
                                    + "WHERE EXISTS (SELECT * FROM C_DocType d WHERE o.C_DocType_ID=d.C_DocType_ID AND d.DocBaseType='API' AND o.AD_Client_ID=d.AD_Client_ID)"
                                    + " AND C_DocType_ID IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set IsSOTrx=N=" + no);

            //	Price List
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET M_PriceList_ID=(SELECT MAX(M_PriceList_ID) FROM M_PriceList p WHERE p.IsDefault='Y'"
                                    + " AND p.C_Currency_ID=o.C_Currency_ID AND p.IsSOPriceList=o.IsSOTrx AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_PriceList_ID IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Default Currency PriceList=" + no);
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET M_PriceList_ID=(SELECT MAX(M_PriceList_ID) FROM M_PriceList p WHERE p.IsDefault='Y'"
                                    + " AND p.IsSOPriceList=o.IsSOTrx AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_PriceList_ID IS NULL AND C_Currency_ID IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Default PriceList=" + no);
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET M_PriceList_ID=(SELECT MAX(M_PriceList_ID) FROM M_PriceList p "
                                    + " WHERE p.C_Currency_ID=o.C_Currency_ID AND p.IsSOPriceList=o.IsSOTrx AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_PriceList_ID IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Currency PriceList=" + no);
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET M_PriceList_ID=(SELECT MAX(M_PriceList_ID) FROM M_PriceList p "
                                    + " WHERE p.IsSOPriceList=o.IsSOTrx AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE M_PriceList_ID IS NULL AND C_Currency_ID IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set PriceList=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No PriceList, ' "
                                    + "WHERE M_PriceList_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No PriceList=" + no);
            }

            //	Payment Rule
            //  We support Payment Rule being input in the login language
            VAdvantage.Login.Language language = VAdvantage.Login.Language.GetLoginLanguage(GetCtx());          //	Base Language
            String AD_Language = language.GetAD_Language();

            sql = new StringBuilder("UPDATE I_Invoice O " +
                                    "SET PaymentRule= " +
                                    "(SELECT R.Value " +
                                    "  FROM AD_Ref_List R " +
                                    "  left outer join AD_Ref_List_Trl RT " +
                                    "  on RT.AD_Ref_List_ID = R.AD_Ref_List_ID and RT.AD_Language = @param " +
                                    "  WHERE R.AD_Reference_ID = 195 and coalesce( RT.Name, R.Name ) = O.PaymentRuleName ) " +
                                    "WHERE PaymentRule is null AND PaymentRuleName IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@param", AD_Language);
            no       = DataBase.DB.ExecuteQuery(sql.ToString(), param, Get_TrxName());
            log.Fine("Set PaymentRule=" + no);
            // do not set a default; if null, the import logic will derive from the business partner
            // do not error in absence of a default

            //	Payment Term
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_PaymentTerm_ID=(SELECT C_PaymentTerm_ID FROM C_PaymentTerm p"
                                    + " WHERE o.PaymentTermValue=p.Value AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE C_PaymentTerm_ID IS NULL AND PaymentTermValue IS NOT NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set PaymentTerm=" + no);
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_PaymentTerm_ID=(SELECT MAX(C_PaymentTerm_ID) FROM C_PaymentTerm p"
                                    + " WHERE p.IsDefault='Y' AND o.AD_Client_ID=p.AD_Client_ID) "
                                    + "WHERE C_PaymentTerm_ID IS NULL AND o.PaymentTermValue IS NULL AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Default PaymentTerm=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No PaymentTerm, ' "
                                    + "WHERE C_PaymentTerm_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No PaymentTerm=" + no);
            }

            //	BP from EMail
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET (C_BPartner_ID,AD_User_ID)=(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u"
                                    + " WHERE o.EMail=u.EMail AND o.AD_Client_ID=u.AD_Client_ID AND u.C_BPartner_ID IS NOT NULL) "
                                    + "WHERE C_BPartner_ID IS NULL AND EMail IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set BP from EMail=" + no);
            //	BP from ContactName
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET (C_BPartner_ID,AD_User_ID)=(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u"
                                    + " WHERE o.ContactName=u.Name AND o.AD_Client_ID=u.AD_Client_ID AND u.C_BPartner_ID IS NOT NULL) "
                                    + "WHERE C_BPartner_ID IS NULL AND ContactName IS NOT NULL"
                                    + " AND EXISTS (SELECT Name FROM AD_User u WHERE o.ContactName=u.Name AND o.AD_Client_ID=u.AD_Client_ID AND u.C_BPartner_ID IS NOT NULL GROUP BY Name HAVING COUNT(*)=1)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set BP from ContactName=" + no);
            //	BP from Value
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_BPartner_ID=(SELECT MAX(C_BPartner_ID) FROM C_BPartner bp"
                                    + " WHERE o.BPartnerValue=bp.Value AND o.AD_Client_ID=bp.AD_Client_ID) "
                                    + "WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set BP from Value=" + no);
            //	Default BP
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_BPartner_ID=(SELECT C_BPartnerCashTrx_ID FROM AD_ClientInfo c"
                                    + " WHERE o.AD_Client_ID=c.AD_Client_ID) "
                                    + "WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NULL AND Name IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Default BP=" + no);

            //	Existing Location ? Exact Match
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID"
                                    + " FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)"
                                    + " WHERE o.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=o.AD_Client_ID"
                                    + " AND DUMP(o.Address1)=DUMP(l.Address1) AND DUMP(o.Address2)=DUMP(l.Address2)"
                                    + " AND DUMP(o.City)=DUMP(l.City) AND DUMP(o.Postal)=DUMP(l.Postal)"
                                    + " AND DUMP(o.C_Region_ID)=DUMP(l.C_Region_ID) AND DUMP(o.C_Country_ID)=DUMP(l.C_Country_ID)) "
                                    + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Found Location=" + no);
            //	Set Location from BPartner
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_BPartner_Location_ID=(SELECT MAX(C_BPartner_Location_ID) FROM C_BPartner_Location l"
                                    + " WHERE l.C_BPartner_ID=o.C_BPartner_ID AND o.AD_Client_ID=l.AD_Client_ID"
                                    + " AND ((l.IsBillTo='Y' AND o.IsSOTrx='Y') OR o.IsSOTrx='N')"
                                    + ") "
                                    + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set BP Location from BP=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No BP Location, ' "
                                    + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No BP Location=" + no);
            }

            //	Set Country

            /**
             * sql = new StringBuilder ("UPDATE I_Invoice o "
             + "SET CountryCode=(SELECT CountryCode FROM C_Country c WHERE c.IsDefault='Y'"
             + " AND c.AD_Client_ID IN (0, o.AD_Client_ID) AND ROWNUM=1) "
             + "WHERE C_BPartner_ID IS NULL AND CountryCode IS NULL AND C_Country_ID IS NULL"
             + " AND I_IsImported<>'Y'").Append (clientCheck);
             + no = DataBase.DB.ExecuteQuery(sql.ToString(),null, Get_TrxName());
             + log.Fine("Set Country Default=" + no);
             **/
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c"
                                    + " WHERE o.CountryCode=c.CountryCode AND c.IsSummary='N' AND c.AD_Client_ID IN (0, o.AD_Client_ID)) "
                                    + "WHERE C_BPartner_ID IS NULL AND C_Country_ID IS NULL AND CountryCode IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Country=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Country, ' "
                                    + "WHERE C_BPartner_ID IS NULL AND C_Country_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Country=" + no);
            }

            //	Set Region
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "Set RegionName=(SELECT MAX(Name) FROM C_Region r"
                                    + " WHERE r.IsDefault='Y' AND r.C_Country_ID=o.C_Country_ID"
                                    + " AND r.AD_Client_ID IN (0, o.AD_Client_ID)) "
                                    + "WHERE C_BPartner_ID IS NULL AND C_Region_ID IS NULL AND RegionName IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Region Default=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r"
                                    + " WHERE r.Name=o.RegionName AND r.C_Country_ID=o.C_Country_ID"
                                    + " AND r.AD_Client_ID IN (0, o.AD_Client_ID)) "
                                    + "WHERE C_BPartner_ID IS NULL AND C_Region_ID IS NULL AND RegionName IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Region=" + no);
            //
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Region, ' "
                                    + "WHERE C_BPartner_ID IS NULL AND C_Region_ID IS NULL "
                                    + " AND EXISTS (SELECT * FROM C_Country c"
                                    + " WHERE c.C_Country_ID=o.C_Country_ID AND c.HasRegion='Y')"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Region=" + no);
            }

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

            //	Tax
            sql = new StringBuilder("UPDATE I_Invoice o "
                                    + "SET C_Tax_ID=(SELECT MAX(C_Tax_ID) FROM C_Tax t"
                                    + " WHERE o.TaxIndicator=t.TaxIndicator AND o.AD_Client_ID=t.AD_Client_ID) "
                                    + "WHERE C_Tax_ID IS NULL AND TaxIndicator IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Tax=" + no);
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Tax, ' "
                                    + "WHERE C_Tax_ID IS NULL AND TaxIndicator IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("Invalid Tax=" + no);
            }

            Commit();

            //	-- New BPartner ---------------------------------------------------

            //	Go through Invoice Records w/o C_BPartner_ID
            sql = new StringBuilder("SELECT * FROM I_Invoice "
                                    + "WHERE I_IsImported='N' AND C_BPartner_ID IS NULL").Append(clientCheck);
            IDataReader idr = null;

            try
            {
                //PreparedStatement pstmt = DataBase.prepareStatement (sql.ToString(), Get_TrxName());
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                while (idr.Read())
                {
                    X_I_Invoice imp = new X_I_Invoice(GetCtx(), idr, Get_TrxName());
                    if (imp.GetBPartnerValue() == null)
                    {
                        if (imp.GetEMail() != null)
                        {
                            imp.SetBPartnerValue(imp.GetEMail());
                        }
                        else if (imp.GetName() != null)
                        {
                            imp.SetBPartnerValue(imp.GetName());
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (imp.GetName() == null)
                    {
                        if (imp.GetContactName() != null)
                        {
                            imp.SetName(imp.GetContactName());
                        }
                        else
                        {
                            imp.SetName(imp.GetBPartnerValue());
                        }
                    }
                    //	BPartner
                    MBPartner bp = MBPartner.Get(GetCtx(), imp.GetBPartnerValue());
                    if (bp == null)
                    {
                        bp = new MBPartner(GetCtx(), -1, Get_TrxName());
                        bp.SetClientOrg(imp.GetAD_Client_ID(), imp.GetAD_Org_ID());
                        bp.SetValue(imp.GetBPartnerValue());
                        bp.SetName(imp.GetName());
                        if (!bp.Save())
                        {
                            continue;
                        }
                    }
                    imp.SetC_BPartner_ID(bp.GetC_BPartner_ID());

                    //	BP Location
                    MBPartnerLocation   bpl  = null;
                    MBPartnerLocation[] bpls = bp.GetLocations(true);
                    for (int i = 0; bpl == null && i < bpls.Length; i++)
                    {
                        if (imp.GetC_BPartner_Location_ID() == bpls[i].GetC_BPartner_Location_ID())
                        {
                            bpl = bpls[i];
                        }
                        //	Same Location ID
                        else if (imp.GetC_Location_ID() == bpls[i].GetC_Location_ID())
                        {
                            bpl = bpls[i];
                        }
                        //	Same Location Info
                        else if (imp.GetC_Location_ID() == 0)
                        {
                            MLocation loc = bpl.GetLocation(false);
                            if (loc.Equals(imp.GetC_Country_ID(), imp.GetC_Region_ID(),
                                           imp.GetPostal(), "", imp.GetCity(),
                                           imp.GetAddress1(), imp.GetAddress2()))
                            {
                                bpl = bpls[i];
                            }
                        }
                    }
                    if (bpl == null)
                    {
                        //	New Location
                        MLocation loc = new MLocation(GetCtx(), 0, Get_TrxName());
                        loc.SetAddress1(imp.GetAddress1());
                        loc.SetAddress2(imp.GetAddress2());
                        loc.SetCity(imp.GetCity());
                        loc.SetPostal(imp.GetPostal());
                        if (imp.GetC_Region_ID() != 0)
                        {
                            loc.SetC_Region_ID(imp.GetC_Region_ID());
                        }
                        loc.SetC_Country_ID(imp.GetC_Country_ID());
                        if (!loc.Save())
                        {
                            continue;
                        }
                        //
                        bpl = new MBPartnerLocation(bp);
                        bpl.SetC_Location_ID(imp.GetC_Location_ID());
                        if (!bpl.Save())
                        {
                            continue;
                        }
                    }
                    imp.SetC_Location_ID(bpl.GetC_Location_ID());
                    imp.SetC_BPartner_Location_ID(bpl.GetC_BPartner_Location_ID());

                    //	User/Contact
                    if (imp.GetContactName() != null ||
                        imp.GetEMail() != null ||
                        imp.GetPhone() != null)
                    {
                        MUser[] users = bp.GetContacts(true);
                        MUser   user  = null;
                        for (int i = 0; user == null && i < users.Length; i++)
                        {
                            String name = users[i].GetName();
                            if (name.Equals(imp.GetContactName()) ||
                                name.Equals(imp.GetName()))
                            {
                                user = users[i];
                                imp.SetAD_User_ID(user.GetAD_User_ID());
                            }
                        }
                        if (user == null)
                        {
                            user = new MUser(bp);
                            if (imp.GetContactName() == null)
                            {
                                user.SetName(imp.GetName());
                            }
                            else
                            {
                                user.SetName(imp.GetContactName());
                            }
                            user.SetEMail(imp.GetEMail());
                            user.SetPhone(imp.GetPhone());
                            if (user.Save())
                            {
                                imp.SetAD_User_ID(user.GetAD_User_ID());
                            }
                        }
                    }
                    imp.Save();
                }       //	for all new BPartners
                idr.Close();

                //
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "CreateBP", e);
            }
            sql = new StringBuilder("UPDATE I_Invoice "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=No BPartner, ' "
                                    + "WHERE C_BPartner_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            if (no != 0)
            {
                log.Warning("No BPartner=" + no);
            }

            Commit();

            //	-- New Invoices -----------------------------------------------------

            int noInsert     = 0;
            int noInsertLine = 0;

            //	Go through Invoice Records w/o
            sql = new StringBuilder("SELECT * FROM I_Invoice "
                                    + "WHERE I_IsImported='N'").Append(clientCheck)
                  .Append(" ORDER BY C_BPartner_ID, C_BPartner_Location_ID, I_Invoice_ID");
            try
            {
                //PreparedStatement pstmt = DataBase.prepareStatement (sql.ToString(), Get_TrxName());
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                //	Group Change
                int    oldC_BPartner_ID          = 0;
                int    oldC_BPartner_Location_ID = 0;
                String oldDocumentNo             = "";
                //
                MInvoice invoice = null;
                int      lineNo  = 0;
                while (idr.Read())
                {
                    X_I_Invoice imp           = new X_I_Invoice(GetCtx(), idr, null);
                    String      cmpDocumentNo = imp.GetDocumentNo();
                    if (cmpDocumentNo == null)
                    {
                        cmpDocumentNo = "";
                    }
                    //	New Invoice
                    if (oldC_BPartner_ID != imp.GetC_BPartner_ID() ||
                        oldC_BPartner_Location_ID != imp.GetC_BPartner_Location_ID() ||
                        !oldDocumentNo.Equals(cmpDocumentNo))
                    {
                        if (invoice != null)
                        {
                            invoice.ProcessIt(_docAction);
                            invoice.Save();
                        }
                        //	Group Change
                        oldC_BPartner_ID          = imp.GetC_BPartner_ID();
                        oldC_BPartner_Location_ID = imp.GetC_BPartner_Location_ID();
                        oldDocumentNo             = imp.GetDocumentNo();
                        if (oldDocumentNo == null)
                        {
                            oldDocumentNo = "";
                        }
                        //
                        invoice = new MInvoice(GetCtx(), 0, null);
                        invoice.SetClientOrg(imp.GetAD_Client_ID(), imp.GetAD_Org_ID());
                        invoice.SetC_DocTypeTarget_ID(imp.GetC_DocType_ID(), true);
                        if (imp.GetDocumentNo() != null)
                        {
                            invoice.SetDocumentNo(imp.GetDocumentNo());
                        }
                        //
                        invoice.SetC_BPartner_ID(imp.GetC_BPartner_ID());
                        invoice.SetC_BPartner_Location_ID(imp.GetC_BPartner_Location_ID());
                        if (imp.GetAD_User_ID() != 0)
                        {
                            invoice.SetAD_User_ID(imp.GetAD_User_ID());
                        }
                        //
                        if (imp.GetDescription() != null)
                        {
                            invoice.SetDescription(imp.GetDescription());
                        }
                        if (imp.GetPaymentRule() != null)
                        {
                            invoice.SetPaymentRule(imp.GetPaymentRule());
                        }
                        invoice.SetC_PaymentTerm_ID(imp.GetC_PaymentTerm_ID());
                        invoice.SetM_PriceList_ID(imp.GetM_PriceList_ID());

                        MPriceList pl = MPriceList.Get(GetCtx(), imp.GetM_PriceList_ID(), Get_TrxName());
                        invoice.SetIsTaxIncluded(pl.IsTaxIncluded());

                        //	SalesRep from Import or the person running the import
                        if (imp.GetSalesRep_ID() != 0)
                        {
                            invoice.SetSalesRep_ID(imp.GetSalesRep_ID());
                        }
                        if (invoice.GetSalesRep_ID() == 0)
                        {
                            invoice.SetSalesRep_ID(GetAD_User_ID());
                        }
                        //
                        if (imp.GetAD_OrgTrx_ID() != 0)
                        {
                            invoice.SetAD_OrgTrx_ID(imp.GetAD_OrgTrx_ID());
                        }
                        if (imp.GetC_Activity_ID() != 0)
                        {
                            invoice.SetC_Activity_ID(imp.GetC_Activity_ID());
                        }
                        if (imp.GetC_Campaign_ID() != 0)
                        {
                            invoice.SetC_Campaign_ID(imp.GetC_Campaign_ID());
                        }
                        if (imp.GetC_Project_ID() != 0)
                        {
                            invoice.SetC_Project_ID(imp.GetC_Project_ID());
                        }
                        //
                        if (imp.GetDateInvoiced() != null)
                        {
                            invoice.SetDateInvoiced(imp.GetDateInvoiced());
                        }
                        if (imp.GetDateAcct() != null)
                        {
                            invoice.SetDateAcct(imp.GetDateAcct());
                        }
                        //
                        invoice.Save();
                        noInsert++;
                        lineNo = 10;
                    }
                    imp.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                    //	New InvoiceLine
                    MInvoiceLine line = new MInvoiceLine(invoice);
                    if (imp.GetLineDescription() != null)
                    {
                        line.SetDescription(imp.GetLineDescription());
                    }
                    line.SetLine(lineNo);
                    lineNo += 10;
                    if (imp.GetM_Product_ID() != 0)
                    {
                        line.SetM_Product_ID(imp.GetM_Product_ID(), true);
                    }
                    line.SetQty(imp.GetQtyOrdered());
                    line.SetPrice();
                    Decimal?price = (Decimal?)imp.GetPriceActual();
                    if (price != null && Env.ZERO.CompareTo(price) != 0)
                    {
                        line.SetPrice(price.Value);
                    }
                    if (imp.GetC_Tax_ID() != 0)
                    {
                        line.SetC_Tax_ID(imp.GetC_Tax_ID());
                    }
                    else
                    {
                        line.SetTax();
                        imp.SetC_Tax_ID(line.GetC_Tax_ID());
                    }
                    Decimal?taxAmt = (Decimal?)imp.GetTaxAmt();
                    if (taxAmt != null && Env.ZERO.CompareTo(taxAmt) != 0)
                    {
                        line.SetTaxAmt(taxAmt);
                    }
                    line.Save();
                    //
                    imp.SetC_InvoiceLine_ID(line.GetC_InvoiceLine_ID());
                    imp.SetI_IsImported(X_I_Invoice.I_ISIMPORTED_Yes);
                    imp.SetProcessed(true);
                    //
                    if (imp.Save())
                    {
                        noInsertLine++;
                    }
                }
                if (invoice != null)
                {
                    invoice.ProcessIt(_docAction);
                    invoice.Save();
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "CreateInvoice", e);
            }

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

        /// <summary>
        /// impoert process
        /// </summary>
        /// <param name="imp">import</param>
        /// <returns>true if processed</returns>
        private bool Process(X_I_Contact imp)
        {
            if (imp.GetEMail() == null || imp.GetEMail().Length == 0)
            {
                return(ProcessFail(imp, "No EMail"));
            }

            MUser user = MUser.Get(GetCtx(), imp.GetEMail(), Get_TrxName());

            //	New User
            if (user == null || user.GetAD_User_ID() == 0)
            {
                if (imp.IsEMailBounced())
                {
                    return(ProcessFail(imp, "No User found with email - cannou set Bounced flag"));
                }
                if (imp.GetContactName() == null || imp.GetContactName().Length == 0)
                {
                    return(ProcessFail(imp, "No Name for User/Contact"));
                }

                user = new MUser(GetCtx(), 0, Get_TrxName());
                user.SetName(imp.GetContactName());
                user.SetDescription(imp.GetContactDescription());
                user.SetEMail(imp.GetEMail());
            }
            //	Existing User
            else
            {
                if (imp.IsEMailBounced())
                {
                    user.SetIsEMailBounced(true);
                    user.SetBouncedInfo(imp.GetBouncedInfo());
                }
            }
            if (!user.Save())
            {
                return(ProcessFail(imp, "Cannot save User"));
            }

            //	Create BP
            if (imp.IsCreateBP())
            {
                if (user.GetC_BPartner_ID() == 0)
                {
                    MBPartner bp = new MBPartner(GetCtx(), 0, Get_TrxName());
                    bp.SetName(user.GetName());
                    if (!bp.Save())
                    {
                        return(ProcessFail(imp, "Cannot create BPartner"));
                    }
                    else
                    {
                        user.SetC_BPartner_ID(bp.GetC_BPartner_ID());
                        if (!user.Save())
                        {
                            return(ProcessFail(imp, "Cannot update User"));
                        }
                    }
                }
                imp.SetC_BPartner_ID(user.GetC_BPartner_ID());
            }

            //	Create Lead
            if (imp.IsCreateLead())
            {
                MLead lead = new MLead(GetCtx(), 0, Get_TrxName());
                lead.SetName(imp.GetContactName());
                lead.SetDescription(imp.GetContactDescription());
                lead.SetAD_User_ID(user.GetAD_User_ID());
                lead.SetC_BPartner_ID(user.GetC_BPartner_ID());
                lead.Save();
                imp.SetC_Lead_ID(lead.GetC_Lead_ID());
            }

            //	Interest Area
            if (imp.GetR_InterestArea_ID() != 0 && user != null)
            {
                MContactInterest ci = MContactInterest.Get(GetCtx(),
                                                           imp.GetR_InterestArea_ID(), user.GetAD_User_ID(),
                                                           true, Get_TrxName());
                ci.Save();              //	don't subscribe or re-activate
            }

            imp.SetAD_User_ID(user.GetAD_User_ID());
            imp.SetI_IsImported(true);
            imp.SetI_ErrorMsg(null);
            imp.Save();
            return(true);
        }       //	process
        }                                  //	prepare

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

            //	****	Prepare	****

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

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

            //	Set BP_Group
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET GroupValue=(SELECT MAX(Value) FROM C_BP_Group g WHERE g.IsDefault='Y'"
                                    + " AND g.AD_Client_ID=i.AD_Client_ID) ");
            sql.Append("WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL"
                       + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Group Default=" + no);
            //
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g"
                                    + " WHERE i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE C_BP_Group_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Group=" + no);
            //
            String ts = DataBase.DB.IsPostgreSQL() ? "COALESCE(I_ErrorMsg,'')" : "I_ErrorMsg";  //java bug, it could not be used directly

            sql = new StringBuilder("UPDATE I_BPartner "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Group, ' "
                                    + "WHERE C_BP_Group_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Config("Invalid Group=" + no);

            //	Set Country

            /**
             * sql = new StringBuilder ("UPDATE I_BPartner i "
             + "SET CountryCode=(SELECT CountryCode FROM C_Country c WHERE c.IsDefault='Y'"
             + " AND c.AD_Client_ID IN (0, i.AD_Client_ID) AND ROWNUM=1) "
             + "WHERE CountryCode IS NULL AND C_Country_ID IS NULL"
             + " AND I_IsImported<>'Y'").Append(clientCheck);
             + no = DataBase.DB.ExecuteQuery(sql.ToString(),null, Get_TrxName());
             + log.Fine("Set Country Default=" + no);
             **/
            //
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c"
                                    + " WHERE i.CountryCode=c.CountryCode AND c.IsSummary='N' AND c.AD_Client_ID IN (0, i.AD_Client_ID)) "
                                    + "WHERE C_Country_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Country=" + no);
            //
            sql = new StringBuilder("UPDATE I_BPartner "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Country, ' "
                                    + "WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Config("Invalid Country=" + no);

            //	Set Region
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "Set RegionName=(SELECT Name FROM C_Region r"
                                    + " WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID"
                                    + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) ");

            /*
             * if (DataBase.isOracle()) //jz
             * {
             *  sql.Append(" AND ROWNUM=1) ");
             * }
             * else
             *  sql.Append(" AND r.UPDATED IN (SELECT MAX(UPDATED) FROM C_Region r1"
             + " WHERE r1.IsDefault='Y' AND r1.C_Country_ID=i.C_Country_ID"
             + " AND r1.AD_Client_ID IN (0, i.AD_Client_ID) ");
             */
            sql.Append("WHERE RegionName IS NULL AND C_Region_ID IS NULL"
                       + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Region Default=" + no);
            //
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r"
                                    + " WHERE r.Name=i.RegionName AND r.C_Country_ID=i.C_Country_ID"
                                    + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) "
                                    + "WHERE C_Region_ID IS NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Region=" + no);
            //
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Region, ' "
                                    + "WHERE C_Region_ID IS NULL "
                                    + " AND EXISTS (SELECT * FROM C_Country c"
                                    + " WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Config("Invalid Region=" + no);

            //	Set Greeting
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g"
                                    + " WHERE i.BPContactGreeting=g.Name AND g.AD_Client_ID IN (0, i.AD_Client_ID)) "
                                    + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Greeting=" + no);
            //
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||'ERR=Invalid Greeting, ' "
                                    + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL"
                                    + " AND I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Config("Invalid Greeting=" + no);

            //	Existing User ?
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET (C_BPartner_ID,AD_User_ID)="
                                    + "(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u "
                                    + "WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").Append(clientCheck);

            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Found EMail User="******"UPDATE I_BPartner i "
                                    + "SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p"
                                    + " WHERE i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Found BPartner=" + no);

            //	Existing Contact ? Match Name
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c"
                                    + " WHERE i.ContactName=c.Name AND i.C_BPartner_ID=c.C_BPartner_ID AND c.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Found Contact=" + no);

            //	Existing Location ? Exact Match
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID"
                                    + " FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)"
                                    + " WHERE i.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=i.AD_Client_ID"
                                    + " AND DUMP(i.Address1)=DUMP(l.Address1) AND DUMP(i.Address2)=DUMP(l.Address2)"
                                    + " AND DUMP(i.City)=DUMP(l.City) AND DUMP(i.Postal)=DUMP(l.Postal) AND DUMP(i.Postal_Add)=DUMP(l.Postal_Add)"
                                    + " AND DUMP(i.C_Region_ID)=DUMP(l.C_Region_ID) AND DUMP(i.C_Country_ID)=DUMP(l.C_Country_ID)) "
                                    + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Found Location=" + no);

            //	Interest Area
            sql = new StringBuilder("UPDATE I_BPartner i "
                                    + "SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia "
                                    + "WHERE i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) "
                                    + "WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL"
                                    + " AND I_IsImported='N'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            log.Fine("Set Interest Area=" + no);


            Commit();
            //	-------------------------------------------------------------------
            int         noInsert = 0;
            int         noUpdate = 0;
            IDataReader idr      = null;

            //	Go through Records
            sql = new StringBuilder("SELECT * FROM I_BPartner "
                                    + "WHERE I_IsImported='N'").Append(clientCheck);
            try
            {
                //PreparedStatement pstmt = DataBase.prepareStatement(sql.ToString(), Get_TrxName());
                //ResultSet rs = pstmt.executeQuery();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName());
                while (idr.Read())
                {
                    X_I_BPartner impBP = new X_I_BPartner(GetCtx(), idr, Get_TrxName());
                    log.Fine("I_BPartner_ID=" + impBP.GetI_BPartner_ID()
                             + ", C_BPartner_ID=" + impBP.GetC_BPartner_ID()
                             + ", C_BPartner_Location_ID=" + impBP.GetC_BPartner_Location_ID()
                             + ", AD_User_ID=" + impBP.GetAD_User_ID());


                    //	****	Create/Update BPartner	****
                    MBPartner bp = null;
                    if (impBP.GetC_BPartner_ID() == 0)  //	Insert new BPartner
                    {
                        bp = new MBPartner(impBP);
                        if (bp.Save())
                        {
                            impBP.SetC_BPartner_ID(bp.GetC_BPartner_ID());
                            log.Finest("Insert BPartner - " + bp.GetC_BPartner_ID());
                            noInsert++;
                        }
                        else
                        {
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("Cannot Insert BPartner")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                    }
                    else                                //	Update existing BPartner
                    {
                        bp = new MBPartner(GetCtx(), impBP.GetC_BPartner_ID(), Get_TrxName());
                        //	if (impBP.getValue() != null)			//	not to overwite
                        //		bp.setValue(impBP.getValue());
                        if (impBP.GetName() != null)
                        {
                            bp.SetName(impBP.GetName());
                            bp.SetName2(impBP.GetName2());
                        }
                        if (impBP.GetDUNS() != null)
                        {
                            bp.SetDUNS(impBP.GetDUNS());
                        }
                        if (impBP.GetTaxID() != null)
                        {
                            bp.SetTaxID(impBP.GetTaxID());
                        }
                        if (impBP.GetNAICS() != null)
                        {
                            bp.SetNAICS(impBP.GetNAICS());
                        }
                        if (impBP.GetC_BP_Group_ID() != 0)
                        {
                            bp.SetC_BP_Group_ID(impBP.GetC_BP_Group_ID());
                        }
                        if (impBP.GetDescription() != null)
                        {
                            bp.SetDescription(impBP.GetDescription());
                        }
                        //
                        if (bp.Save())
                        {
                            log.Finest("Update BPartner - " + bp.GetC_BPartner_ID());
                            noUpdate++;
                        }
                        else
                        {
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("' Cannot Update BPartner' ") //jz
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                    }

                    //	****	Create/Update BPartner Location	****
                    MBPartnerLocation bpl = null;
                    if (impBP.GetC_BPartner_Location_ID() != 0)         //	Update Location
                    {
                        bpl = new MBPartnerLocation(GetCtx(), impBP.GetC_BPartner_Location_ID(), Get_TrxName());
                        MLocation location = new MLocation(GetCtx(), bpl.GetC_Location_ID(), Get_TrxName());
                        location.SetC_Country_ID(impBP.GetC_Country_ID());
                        location.SetC_Region_ID(impBP.GetC_Region_ID());
                        location.SetCity(impBP.GetCity());
                        location.SetAddress1(impBP.GetAddress1());
                        location.SetAddress2(impBP.GetAddress2());
                        location.SetPostal(impBP.GetPostal());
                        location.SetPostal_Add(impBP.GetPostal_Add());
                        location.SetRegionName(impBP.GetRegionName());
                        if (!location.Save())
                        {
                            log.Warning("Location not updated");
                        }
                        else
                        {
                            bpl.SetC_Location_ID(location.GetC_Location_ID());
                        }
                        if (impBP.GetPhone() != null)
                        {
                            bpl.SetPhone(impBP.GetPhone());
                        }
                        if (impBP.GetPhone2() != null)
                        {
                            bpl.SetPhone2(impBP.GetPhone2());
                        }
                        if (impBP.GetFax() != null)
                        {
                            bpl.SetFax(impBP.GetFax());
                        }
                        bpl.Save();
                    }
                    else        //	New Location
                    if (impBP.GetC_Country_ID() != 0 &&
                        impBP.GetAddress1() != null &&
                        impBP.GetCity() != null)
                    {
                        MLocation location = new MLocation(GetCtx(), impBP.GetC_Country_ID(),
                                                           impBP.GetC_Region_ID(), impBP.GetCity(), Get_TrxName());
                        location.SetAddress1(impBP.GetAddress1());
                        location.SetAddress2(impBP.GetAddress2());
                        location.SetPostal(impBP.GetPostal());
                        location.SetPostal_Add(impBP.GetPostal_Add());
                        location.SetRegionName(impBP.GetRegionName());
                        if (location.Save())
                        {
                            log.Finest("Insert Location - " + location.GetC_Location_ID());
                        }
                        else
                        {
                            Rollback();
                            noInsert--;
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("Cannot Insert Location")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                        //
                        bpl = new MBPartnerLocation(bp);
                        bpl.SetC_Location_ID(location.GetC_Location_ID());
                        bpl.SetPhone(impBP.GetPhone());
                        bpl.SetPhone2(impBP.GetPhone2());
                        bpl.SetFax(impBP.GetFax());
                        if (bpl.Save())
                        {
                            log.Finest("Insert BP Location - " + bpl.GetC_BPartner_Location_ID());
                            impBP.SetC_BPartner_Location_ID(bpl.GetC_BPartner_Location_ID());
                        }
                        else
                        {
                            Rollback();
                            noInsert--;
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("Cannot Insert BPLocation")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                    }

                    //	****	Create/Update Contact	****
                    MUser user = null;
                    if (impBP.GetAD_User_ID() != 0)
                    {
                        user = new MUser(GetCtx(), impBP.GetAD_User_ID(), Get_TrxName());
                        if (user.GetC_BPartner_ID() == 0)
                        {
                            user.SetC_BPartner_ID(bp.GetC_BPartner_ID());
                        }
                        else if (user.GetC_BPartner_ID() != bp.GetC_BPartner_ID())
                        {
                            Rollback();
                            noInsert--;
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("BP of User <> BP")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                        if (impBP.GetC_Greeting_ID() != 0)
                        {
                            user.SetC_Greeting_ID(impBP.GetC_Greeting_ID());
                        }
                        String name = impBP.GetContactName();
                        if (name == null || name.Length == 0)
                        {
                            name = impBP.GetEMail();
                        }
                        user.SetName(name);
                        if (impBP.GetTitle() != null)
                        {
                            user.SetTitle(impBP.GetTitle());
                        }
                        if (impBP.GetContactDescription() != null)
                        {
                            user.SetDescription(impBP.GetContactDescription());
                        }
                        if (impBP.GetComments() != null)
                        {
                            user.SetComments(impBP.GetComments());
                        }
                        if (impBP.GetPhone() != null)
                        {
                            user.SetPhone(impBP.GetPhone());
                        }
                        if (impBP.GetPhone2() != null)
                        {
                            user.SetPhone2(impBP.GetPhone2());
                        }
                        if (impBP.GetFax() != null)
                        {
                            user.SetFax(impBP.GetFax());
                        }
                        if (impBP.GetEMail() != null)
                        {
                            user.SetEMail(impBP.GetEMail());
                        }
                        if (impBP.GetBirthday() != null)
                        {
                            user.SetBirthday(impBP.GetBirthday());
                        }
                        if (bpl != null)
                        {
                            user.SetC_BPartner_Location_ID(bpl.GetC_BPartner_Location_ID());
                        }
                        if (user.Save())
                        {
                            log.Finest("Update BP Contact - " + user.GetAD_User_ID());
                        }
                        else
                        {
                            Rollback();
                            noInsert--;
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("Cannot Update BP Contact")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                    }
                    else        //	New Contact
                    if (impBP.GetContactName() != null || impBP.GetEMail() != null)
                    {
                        user = new MUser(bp);
                        if (impBP.GetC_Greeting_ID() != 0)
                        {
                            user.SetC_Greeting_ID(impBP.GetC_Greeting_ID());
                        }
                        String name = impBP.GetContactName();
                        if (name == null || name.Length == 0)
                        {
                            name = impBP.GetEMail();
                        }
                        user.SetName(name);
                        user.SetTitle(impBP.GetTitle());
                        user.SetDescription(impBP.GetContactDescription());
                        user.SetComments(impBP.GetComments());
                        user.SetPhone(impBP.GetPhone());
                        user.SetPhone2(impBP.GetPhone2());
                        user.SetFax(impBP.GetFax());
                        user.SetEMail(impBP.GetEMail());
                        user.SetBirthday(impBP.GetBirthday());
                        if (bpl != null)
                        {
                            user.SetC_BPartner_Location_ID(bpl.GetC_BPartner_Location_ID());
                        }
                        if (user.Save())
                        {
                            log.Finest("Insert BP Contact - " + user.GetAD_User_ID());
                            impBP.SetAD_User_ID(user.GetAD_User_ID());
                        }
                        else
                        {
                            Rollback();
                            noInsert--;
                            sql = new StringBuilder("UPDATE I_BPartner i "
                                                    + "SET I_IsImported='E', I_ErrorMsg=" + ts + "||")
                                  .Append("Cannot Insert BPContact")
                                  .Append("WHERE I_BPartner_ID=").Append(impBP.GetI_BPartner_ID());
                            DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
                            continue;
                        }
                    }

                    //	Interest Area
                    if (impBP.GetR_InterestArea_ID() != 0 && user != null)
                    {
                        MContactInterest ci = MContactInterest.Get(GetCtx(),
                                                                   impBP.GetR_InterestArea_ID(), user.GetAD_User_ID(),
                                                                   true, Get_TrxName());
                        ci.Save();              //	don't subscribe or re-activate
                    }
                    //
                    impBP.SetI_IsImported(X_I_BPartner.I_ISIMPORTED_Yes);
                    impBP.SetProcessed(true);
                    impBP.SetProcessing(false);
                    impBP.Save();
                    Commit();
                }       //	for all I_Product
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "", e);
                Rollback();
            }

            //	Set Error to indicator to not imported
            sql = new StringBuilder("UPDATE I_BPartner "
                                    + "SET I_IsImported='N', Updated=SysDate "
                                    + "WHERE I_IsImported<>'Y'").Append(clientCheck);
            no = DataBase.DB.ExecuteQuery(sql.ToString(), null, Get_TrxName());
            AddLog(0, null, Utility.Util.GetValueOfDecimal(no), "@Errors@");
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noInsert), "@C_BPartner_ID@: @Inserted@");
            AddLog(0, null, Utility.Util.GetValueOfDecimal(noUpdate), "@C_BPartner_ID@: @Updated@");
            return("");
        }       //	doIt
        protected override string DoIt()
        {
            VLogger log = VLogger.GetVLogger(this.GetType().FullName);

            log.Log(Level.SEVERE, "UserPassword Change Log=>" + Convert.ToString(p_AD_User_ID));
            if (p_AD_User_ID == -1)
            {
                p_AD_User_ID = GetAD_User_ID();
            }

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


            if (!current.IsAdministrator() && p_AD_User_ID != GetAD_User_ID() && user.HasRole())
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            // SuperUser and System passwords can only be updated by themselves
            if (user.IsSystemAdministrator() && p_AD_User_ID != GetAD_User_ID() && GetAD_User_ID() != 100)
            {
                throw new ArgumentException("@UserCannotUpdate@");
            }

            log.Log(Level.SEVERE, "UserPassword Change Log Step Check for valid user=>" + Convert.ToString(p_AD_User_ID));
            if (string.IsNullOrEmpty(p_CurrentPassword))
            {
                if (string.IsNullOrEmpty(p_OldPassword))
                {
                    throw new ArgumentException("@OldPasswordMandatory@");
                }
                else if (!p_OldPassword.Equals(user.GetPassword()))
                {
                    if (!SecureEngine.Encrypt(p_OldPassword).Equals(user.GetPassword()))
                    {
                        throw new ArgumentException("@OldPasswordNoMatch@");
                    }
                }
            }

            else if (!p_CurrentPassword.Equals(current.GetPassword()))
            {
                throw new ArgumentException("@OldPasswordNoMatch@");
            }

            string validatePwd = Common.Common.ValidatePassword(null, p_NewPassword, p_NewPassword);

            if (validatePwd.Length > 0)
            {
                throw new ArgumentException(Msg.GetMsg(GetCtx(), validatePwd));
            }

            log.Log(Level.SEVERE, "UserPassword Change Log Step Password Change=>" + Convert.ToString(p_AD_User_ID));
            String originalPwd = p_NewPassword;

            String sql = "UPDATE AD_User SET Updated=SYSDATE,FailedloginCount=0, UpdatedBy=" + GetAD_User_ID();

            if (user.GetAD_User_ID() == current.GetAD_User_ID())
            {
                Common.Common.UpdatePasswordAndValidity(p_NewPassword, p_AD_User_ID, GetAD_User_ID(), -1, GetCtx());
            }
            else
            {
                sql += ",  PasswordExpireOn = null";
            }


            if (!string.IsNullOrEmpty(p_NewPassword))
            {
                MColumn column = MColumn.Get(GetCtx(), 417); // Password Column
                if (column.IsEncrypted())
                {
                    p_NewPassword = SecureEngine.Encrypt(p_NewPassword);
                }
                sql += ", Password="******", Email=" + GlobalVariable.TO_STRING(p_NewEMail);
            }
            if (!string.IsNullOrEmpty(p_NewEMailUser))
            {
                sql += ", EmailUser="******", EmailUserPW=" + GlobalVariable.TO_STRING(p_NewEMailUserPW);
            }
            sql += " WHERE AD_User_ID=" + p_AD_User_ID;
            log.Log(Level.SEVERE, "UserPassword Change Log=>" + sql);
            int iRes = DB.ExecuteQuery(sql, null, Get_Trx());

            if (iRes > 0)
            {
                return("@OK@");
            }
            else
            {
                return("@Error@");
            }
        }