Adempiere 3.1.2

This commit is contained in:
vpj-cd 2006-12-07 03:20:51 +00:00
parent 39a4889c05
commit 6c5fa90281
33 changed files with 13926 additions and 12423 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,95 +3,216 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
/** /**
* BP Bank Account Model * BP Bank Account Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MBPBankAccount.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ * @version $Id: MBPBankAccount.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/ */
public class MBPBankAccount extends X_C_BP_BankAccount public class MBPBankAccount extends X_C_BP_BankAccount
{ {
/** /**
* Get Accounst Of BPartner
* @param ctx context
* @param C_BPartner_ID bpartner
* @return
*/
public static MBPBankAccount[] getOfBPartner (Properties ctx, int C_BPartner_ID)
{
String sql = "SELECT * FROM C_BP_BankAccount WHERE C_BPartner_ID=? AND IsActive='Y'";
ArrayList<MBPBankAccount> list = new ArrayList<MBPBankAccount>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
list.add(new MBPBankAccount(ctx, rs, null));
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try {
if (pstmt != null)
pstmt.close();
pstmt = null;
} catch (Exception e) {
pstmt = null;
}
MBPBankAccount[] retValue = new MBPBankAccount[list.size()];
list.toArray(retValue);
return retValue;
} // getOfBPartner
/** Logger */
private static CLogger s_log = CLogger.getCLogger(MBPBankAccount.class);
/**************************************************************************
* Constructor * Constructor
* @param ctx context * @param ctx context
* @param C_BP_BankAccount_ID BP bank account * @param C_BP_BankAccount_ID BP bank account
* @param trxName transaction * @param trxName transaction
*/ */
public MBPBankAccount (Properties ctx, int C_BP_BankAccount_ID, String trxName) public MBPBankAccount (Properties ctx, int C_BP_BankAccount_ID, String trxName)
{ {
super (ctx, C_BP_BankAccount_ID, trxName); super (ctx, C_BP_BankAccount_ID, trxName);
if (C_BP_BankAccount_ID == 0) if (C_BP_BankAccount_ID == 0)
{ {
// setC_BPartner_ID (0); // setC_BPartner_ID (0);
setIsACH (false); setIsACH (false);
setBPBankAcctUse(BPBANKACCTUSE_Both);
} }
} // MBP_BankAccount } // MBP_BankAccount
/** /**
* Constructor * Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MBPBankAccount (Properties ctx, ResultSet rs, String trxName) public MBPBankAccount (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MBP_BankAccount } // MBP_BankAccount
/** /**
* Constructor * Constructor
* @param ctx context * @param ctx context
* @param bp BP * @param bp BP
* @param bpc BP Contact * @param bpc BP Contact
* @param location Location * @param location Location
*/ */
public MBPBankAccount (Properties ctx, MBPartner bp, MUser bpc, MLocation location) public MBPBankAccount (Properties ctx, MBPartner bp, MUser bpc, MLocation location)
{ {
super(ctx, 0, bp.get_TrxName()); this(ctx, 0, bp.get_TrxName());
setIsACH (false); setIsACH (false);
// //
setC_BPartner_ID(bp.getC_BPartner_ID()); setC_BPartner_ID(bp.getC_BPartner_ID());
// //
setA_Name(bpc.getName()); setA_Name(bpc.getName());
setA_EMail(bpc.getEMail()); setA_EMail(bpc.getEMail());
// //
setA_Street(location.getAddress1()); setA_Street(location.getAddress1());
setA_City(location.getCity()); setA_City(location.getCity());
setA_Zip(location.getPostal()); setA_Zip(location.getPostal());
setA_State(location.getRegionName(true)); setA_State(location.getRegionName(true));
setA_Country(location.getCountryName()); setA_Country(location.getCountryName());
} // MBP_BankAccount } // MBP_BankAccount
/** Bank Link */
private MBank m_bank = null;
/*************************************************************************/ /**
* Is Direct Deposit
* @return true if dd
*/
public boolean isDirectDeposit()
{
if (!isACH())
return false;
String s = getBPBankAcctUse();
if (s == null)
return true;
return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDeposit));
} // isDirectDeposit
/**
* Is Direct Debit
* @return true if dd
*/
public boolean isDirectDebit()
{
if (!isACH())
return false;
String s = getBPBankAcctUse();
if (s == null)
return true;
return (s.equals(BPBANKACCTUSE_Both) || s.equals(BPBANKACCTUSE_DirectDebit));
} // isDirectDebit
/**
* Get Bank
* @return bank
*/
public MBank getBank()
{
int C_BP_BankAccount_ID = getC_BP_BankAccount_ID();
if (C_BP_BankAccount_ID == 0)
return null;
if (m_bank == null)
m_bank = new MBank (getCtx(), C_BP_BankAccount_ID, get_TrxName());
return m_bank;
} // getBank
/**
* Get Routing No
* @return routing No
*/
public String getRoutingNo()
{
MBank bank = getBank();
String rt = super.getRoutingNo();
if (bank != null)
rt = bank.getRoutingNo();
return rt;
} // getRoutingNo
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave(boolean newRecord)
{
// maintain routing on bank level
if (isACH() && getBank() != null)
setRoutingNo(null);
//
return true;
} // beforeSave
/** /**
* String Representation * String Representation
* @return info * @return info
*/ */
public String toString () public String toString ()
{ {
StringBuffer sb = new StringBuffer ("MBP_BankAccount[") StringBuffer sb = new StringBuffer ("MBP_BankAccount[")
.append (get_ID ()) .append (get_ID ())
.append(", Name=").append(getA_Name()) .append(", Name=").append(getA_Name())
.append ("]"); .append ("]");
return sb.toString (); return sb.toString ();
} // toString } // toString
} // MBPBankAccount } // MBPBankAccount

View File

@ -3,237 +3,238 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.text.*; import java.text.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.apache.ecs.xhtml.*; import org.apache.ecs.xhtml.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Chat Model * Chat Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MChat.java,v 1.4 2006/07/30 00:51:05 jjanke Exp $ * @version $Id: MChat.java,v 1.4 2006/07/30 00:51:05 jjanke Exp $
*/ */
public class MChat extends X_CM_Chat public class MChat extends X_CM_Chat
{ {
/** /**
* Get Chats Of Table - of client in context * Get Chats Of Table - of client in context
* @param ctx context * @param ctx context
* @param AD_Table_ID table * @param AD_Table_ID table
* @return array of chats * @return array of chats
*/ */
public static MChat[] getOfTable (Properties ctx, int AD_Table_ID) public static MChat[] getOfTable (Properties ctx, int AD_Table_ID)
{ {
int AD_Client_ID = Env.getAD_Client_ID(ctx); int AD_Client_ID = Env.getAD_Client_ID(ctx);
ArrayList<MChat> list = new ArrayList<MChat>(); ArrayList<MChat> list = new ArrayList<MChat>();
// //
String sql = "SELECT * FROM CM_Chat " String sql = "SELECT * FROM CM_Chat "
+ "WHERE AD_Client_ID=? AND AD_Table_ID=? ORDER BY Record_ID"; + "WHERE AD_Client_ID=? AND AD_Table_ID=? ORDER BY Record_ID";
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, null); pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, AD_Client_ID); pstmt.setInt (1, AD_Client_ID);
pstmt.setInt (2, AD_Table_ID); pstmt.setInt (2, AD_Table_ID);
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
list.add (new MChat (ctx, rs, null)); list.add (new MChat (ctx, rs, null));
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
s_log.log (Level.SEVERE, sql, e); s_log.log (Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
// //
MChat[] retValue = new MChat[list.size()]; MChat[] retValue = new MChat[list.size()];
list.toArray (retValue); list.toArray (retValue);
return retValue; return retValue;
} // get } // get
/** Logger */ /** Logger */
private static CLogger s_log = CLogger.getCLogger (MChat.class); private static CLogger s_log = CLogger.getCLogger (MChat.class);
/************************************************************************** /**************************************************************************
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param CM_Chat_ID id * @param CM_Chat_ID id
* @param trxName transcation * @param trxName transcation
*/ */
public MChat (Properties ctx, int CM_Chat_ID, String trxName) public MChat (Properties ctx, int CM_Chat_ID, String trxName)
{ {
super (ctx, CM_Chat_ID, trxName); super (ctx, CM_Chat_ID, trxName);
if (CM_Chat_ID == 0) if (CM_Chat_ID == 0)
{ {
// setAD_Table_ID (0); // setAD_Table_ID (0);
// setRecord_ID (0); // setRecord_ID (0);
setConfidentialType (CONFIDENTIALTYPE_PublicInformation); setConfidentialType (CONFIDENTIALTYPE_PublicInformation);
setModerationType (MODERATIONTYPE_NotModerated);
// setDescription (null); // setDescription (null);
} }
} // MChat } // MChat
/** /**
* Full Constructor * Full Constructor
* @param ctx context * @param ctx context
* @param AD_Table_ID table * @param AD_Table_ID table
* @param Record_ID record * @param Record_ID record
* @param Description description * @param Description description
* @param trxName transaction * @param trxName transaction
*/ */
public MChat (Properties ctx, int AD_Table_ID, int Record_ID, public MChat (Properties ctx, int AD_Table_ID, int Record_ID,
String Description, String trxName) String Description, String trxName)
{ {
this (ctx, 0, trxName); this (ctx, 0, trxName);
setAD_Table_ID (AD_Table_ID); setAD_Table_ID (AD_Table_ID);
setRecord_ID (Record_ID); setRecord_ID (Record_ID);
setDescription (Description); setDescription (Description);
} // MChat } // MChat
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MChat (Properties ctx, ResultSet rs, String trxName) public MChat (Properties ctx, ResultSet rs, String trxName)
{ {
super (ctx, rs, trxName); super (ctx, rs, trxName);
} // MChat } // MChat
/** The Lines */ /** The Lines */
private MChatEntry[] m_entries = null; private MChatEntry[] m_entries = null;
/** Date Format */ /** Date Format */
private SimpleDateFormat m_format = null; private SimpleDateFormat m_format = null;
/** /**
* Get Entries * Get Entries
* @param reload reload data * @param reload reload data
* @return array of lines * @return array of lines
*/ */
public MChatEntry[] getEntries (boolean reload) public MChatEntry[] getEntries (boolean reload)
{ {
if (m_entries != null && !reload) if (m_entries != null && !reload)
return m_entries; return m_entries;
ArrayList<MChatEntry> list = new ArrayList<MChatEntry>(); ArrayList<MChatEntry> list = new ArrayList<MChatEntry>();
String sql = "SELECT * FROM CM_ChatEntry WHERE CM_Chat_ID=? ORDER BY Created"; String sql = "SELECT * FROM CM_ChatEntry WHERE CM_Chat_ID=? ORDER BY Created";
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, null); pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getCM_Chat_ID()); pstmt.setInt (1, getCM_Chat_ID());
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
list.add (new MChatEntry (getCtx(), rs, get_TrxName())); list.add (new MChatEntry (getCtx(), rs, get_TrxName()));
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
log.log (Level.SEVERE, sql, e); log.log (Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
// //
m_entries = new MChatEntry[list.size ()]; m_entries = new MChatEntry[list.size ()];
list.toArray (m_entries); list.toArray (m_entries);
return m_entries; return m_entries;
} // getEntries } // getEntries
/** /**
* Set Description * Set Description
* *
* @param Description * @param Description
*/ */
public void setDescription (String Description) public void setDescription (String Description)
{ {
if (Description != null && Description.length() > 0) if (Description != null && Description.length() > 0)
super.setDescription (Description); super.setDescription (Description);
else else
super.setDescription (getAD_Table_ID() + "#" + getRecord_ID()); super.setDescription (getAD_Table_ID() + "#" + getRecord_ID());
} // setDescription } // setDescription
/** /**
* Get History as htlp paragraph * Get History as htlp paragraph
* @param ConfidentialType confidentiality * @param ConfidentialType confidentiality
* @return html paragraph * @return html paragraph
*/ */
public p getHistory (String ConfidentialType) public p getHistory (String ConfidentialType)
{ {
p history = new p(); p history = new p();
getEntries(false); getEntries(false);
boolean first = true; boolean first = true;
for (int i = 0; i < m_entries.length; i++) for (int i = 0; i < m_entries.length; i++)
{ {
MChatEntry entry = m_entries[i]; MChatEntry entry = m_entries[i];
if (!entry.isActive() || !entry.isConfidentialType(ConfidentialType)) if (!entry.isActive() || !entry.isConfidentialType(ConfidentialType))
continue; continue;
if (first) if (first)
first = false; first = false;
else else
history.addElement(new hr()); history.addElement(new hr());
// User & Date // User & Date
b b = new b(); b b = new b();
MUser user = MUser.get(getCtx(), entry.getCreatedBy()); MUser user = MUser.get(getCtx(), entry.getCreatedBy());
b.addElement(user.getName()); b.addElement(user.getName());
b.addElement(" \t"); b.addElement(" \t");
Timestamp created = entry.getCreated(); Timestamp created = entry.getCreated();
if (m_format == null) if (m_format == null)
m_format = DisplayType.getDateFormat(DisplayType.DateTime); m_format = DisplayType.getDateFormat(DisplayType.DateTime);
b.addElement(m_format.format(created)); b.addElement(m_format.format(created));
history.addElement(b); history.addElement(b);
// history.addElement(new br()); // history.addElement(new br());
// //
p p = new p(); p p = new p();
String data = entry.getCharacterData(); String data = entry.getCharacterData();
data = Util.maskHTML(data, true); data = Util.maskHTML(data, true);
p.addElement(data); p.addElement(data);
history.addElement(p); history.addElement(p);
} // entry } // entry
// //
return history; return history;
} // getHistory } // getHistory
} // MChat } // MChat

View File

@ -3,91 +3,116 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import org.compiere.util.*;
/** /**
* Chat Entry Model * Chat Entry Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MChatEntry.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $ * @version $Id: MChatEntry.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/ */
public class MChatEntry extends X_CM_ChatEntry public class MChatEntry extends X_CM_ChatEntry
{ {
/** /**
* Standard Constructor * Standard Constructor
* @param ctx cintext * @param ctx cintext
* @param CM_ChatEntry_ID id * @param CM_ChatEntry_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName) public MChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName)
{ {
super (ctx, CM_ChatEntry_ID, trxName); super (ctx, CM_ChatEntry_ID, trxName);
if (CM_ChatEntry_ID == 0)
{
setChatEntryType (CHATENTRYTYPE_NoteFlat); // N
setConfidentialType (CONFIDENTIALTYPE_PublicInformation);
}
} // MChatEntry } // MChatEntry
/** /**
* Parent Constructor * Parent Constructor
* @param chat parent * @param chat parent
* @param data text * @param data text
*/ */
public MChatEntry (MChat chat, String data) public MChatEntry (MChat chat, String data)
{ {
this (chat.getCtx(), 0, chat.get_TrxName()); this (chat.getCtx(), 0, chat.get_TrxName());
setCM_Chat_ID(chat.getCM_Chat_ID()); setCM_Chat_ID(chat.getCM_Chat_ID());
setConfidentialType(chat.getConfidentialType()); setConfidentialType(chat.getConfidentialType());
setCharacterData(data); setCharacterData(data);
setChatEntryType (CHATENTRYTYPE_NoteFlat); // N
} // MChatEntry } // MChatEntry
/** /**
* Load Constructor * Thread Constructor
* @param ctx context * @param entry peer
* @param rs result set * @param data text
* @param trxName transaction
*/ */
public MChatEntry (Properties ctx, ResultSet rs, String trxName) public MChatEntry (MChatEntry peer, String data)
{ {
super (ctx, rs, trxName); this (peer.getCtx(), 0, peer.get_TrxName());
setCM_Chat_ID(peer.getCM_Chat_ID());
setCM_ChatEntryParent_ID (peer.getCM_ChatEntryParent_ID());
// Set GrandParent
int id = peer.getCM_ChatEntryGrandParent_ID();
if (id == 0)
id = peer.getCM_ChatEntryParent_ID();
setCM_ChatEntryGrandParent_ID (id);
setConfidentialType(peer.getConfidentialType());
setCharacterData(data);
setChatEntryType (CHATENTRYTYPE_ForumThreaded);
} // MChatEntry } // MChatEntry
/** /**
* Can be published * Load Constructor
* @param ConfidentialType minimum confidential type * @param ctx context
* @return true if withing confidentiality * @param rs result set
*/ * @param trxName transaction
public boolean isConfidentialType(String ConfidentialType) */
{ public MChatEntry (Properties ctx, ResultSet rs, String trxName)
String ct = getConfidentialType(); {
if (ConfidentialType == null super (ctx, rs, trxName);
|| CONFIDENTIALTYPE_PublicInformation.equals(ct)) } // MChatEntry
return true;
if (CONFIDENTIALTYPE_PartnerConfidential.equals(ct)) /**
{ * Can be published
return CONFIDENTIALTYPE_PartnerConfidential.equals(ConfidentialType); * @param ConfidentialType minimum confidential type
} * @return true if withing confidentiality
else if (CONFIDENTIALTYPE_PrivateInformation.equals(ct)) */
{ public boolean isConfidentialType(String ConfidentialType)
return CONFIDENTIALTYPE_Internal.equals(ConfidentialType) {
|| CONFIDENTIALTYPE_PrivateInformation.equals(ConfidentialType); String ct = getConfidentialType();
} if (ConfidentialType == null
else if (CONFIDENTIALTYPE_Internal.equals(ct)) || CONFIDENTIALTYPE_PublicInformation.equals(ct))
{ return true;
return CONFIDENTIALTYPE_Internal.equals(ConfidentialType); if (CONFIDENTIALTYPE_PartnerConfidential.equals(ct))
} {
return false; return CONFIDENTIALTYPE_PartnerConfidential.equals(ConfidentialType);
} // }
else if (CONFIDENTIALTYPE_PrivateInformation.equals(ct))
} // MChatEntry {
return CONFIDENTIALTYPE_Internal.equals(ConfidentialType)
|| CONFIDENTIALTYPE_PrivateInformation.equals(ConfidentialType);
}
else if (CONFIDENTIALTYPE_Internal.equals(ct))
{
return CONFIDENTIALTYPE_Internal.equals(ConfidentialType);
}
return false;
} //
} // MChatEntry

View File

@ -3,73 +3,75 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Chat Type Model * Chat Type Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MChatType.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $ * @version $Id: MChatType.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/ */
public class MChatType extends X_CM_ChatType public class MChatType extends X_CM_ChatType
{ {
/** /**
* Get MChatType from Cache * Get MChatType from Cache
* @param ctx context * @param ctx context
* @param CM_ChatType_ID id * @param CM_ChatType_ID id
* @return MChatType * @return MChatType
*/ */
public static MChatType get (Properties ctx, int CM_ChatType_ID) public static MChatType get (Properties ctx, int CM_ChatType_ID)
{ {
Integer key = new Integer (CM_ChatType_ID); Integer key = new Integer (CM_ChatType_ID);
MChatType retValue = (MChatType)s_cache.get (key); MChatType retValue = (MChatType)s_cache.get (key);
if (retValue != null) if (retValue != null)
return retValue; return retValue;
retValue = new MChatType (ctx, CM_ChatType_ID, null); retValue = new MChatType (ctx, CM_ChatType_ID, null);
if (retValue.get_ID () != CM_ChatType_ID) if (retValue.get_ID () != CM_ChatType_ID)
s_cache.put (key, retValue); s_cache.put (key, retValue);
return retValue; return retValue;
} // get } // get
/** Cache */ /** Cache */
private static CCache<Integer, MChatType> s_cache private static CCache<Integer, MChatType> s_cache
= new CCache<Integer, MChatType> ("CM_ChatType", 20); = new CCache<Integer, MChatType> ("CM_ChatType", 20);
/** /**
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param CM_ChatType_ID id * @param CM_ChatType_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MChatType (Properties ctx, int CM_ChatType_ID, String trxName) public MChatType (Properties ctx, int CM_ChatType_ID, String trxName)
{ {
super (ctx, CM_ChatType_ID, trxName); super (ctx, CM_ChatType_ID, trxName);
if (CM_ChatType_ID == 0)
setModerationType (MODERATIONTYPE_NotModerated);
} // MChatType } // MChatType
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MChatType (Properties ctx, ResultSet rs, String trxName) public MChatType (Properties ctx, ResultSet rs, String trxName)
{ {
super (ctx, rs, trxName); super (ctx, rs, trxName);
} // MChatType } // MChatType
} // MChatType } // MChatType

File diff suppressed because it is too large Load Diff

View File

@ -3,115 +3,160 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* CStage Element * CStage Element
* *
* @author Yves Sandfort * @author Yves Sandfort
* @version $Id$ * @version $Id$
*/ */
public class MContainerElement extends X_CM_Container_Element public class MContainerElement extends X_CM_Container_Element
{ {
/** serialVersionUID */
private static final long serialVersionUID = 7230036377422361941L;
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MContainer.class);
/**
* get Container Element by ID
* @param ctx
* @param CM_ContainerElement_ID
* @param trxName
* @return ContainerElement
*/
public static MContainerElement get(Properties ctx, int CM_ContainerElement_ID, String trxName) {
MContainerElement thisContainerElement = null;
String sql = "SELECT * FROM CM_Container_Element WHERE CM_Container_Element_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, CM_ContainerElement_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
thisContainerElement = (new MContainerElement(ctx, rs, trxName));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return thisContainerElement;
}
/*************************************************************************** /***************************************************************************
* Standard Constructor * Standard Constructor
* *
* @param ctx context * @param ctx context
* @param CM_Container_Element_ID id * @param CM_Container_Element_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MContainerElement (Properties ctx, int CM_Container_Element_ID, String trxName) public MContainerElement (Properties ctx, int CM_Container_Element_ID, String trxName)
{ {
super (ctx, CM_Container_Element_ID, trxName); super (ctx, CM_Container_Element_ID, trxName);
if (CM_Container_Element_ID == 0) if (CM_Container_Element_ID == 0)
{ {
setIsValid(false); setIsValid(false);
} }
} // MContainerElement } // MContainerElement
/** /**
* Load Constructor * Load Constructor
* *
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MContainerElement (Properties ctx, ResultSet rs, String trxName) public MContainerElement (Properties ctx, ResultSet rs, String trxName)
{ {
super (ctx, rs, trxName); super (ctx, rs, trxName);
} // MContainerElement } // MContainerElement
/** Parent */ /** Parent */
private MContainer m_parent = null; private MContainer m_parent = null;
/** /**
* Get Container get's related Container * Get Container get's related Container
* @return MContainer * @return MContainer
*/ */
public MContainer getParent() public MContainer getParent()
{ {
if (m_parent == null) if (m_parent == null)
m_parent = new MContainer (getCtx(), getCM_Container_ID(), get_TrxName()); m_parent = new MContainer (getCtx(), getCM_Container_ID(), get_TrxName());
return m_parent; return m_parent;
/** No reason to do this ?? - should never return null - always there - JJ /** No reason to do this ?? - should never return null - always there - JJ
int[] thisContainer = MContainer.getAllIDs("CM_Container","CM_Container_ID=" + this.getCM_Container_ID(), get_TrxName()); int[] thisContainer = MContainer.getAllIDs("CM_Container","CM_Container_ID=" + this.getCM_Container_ID(), get_TrxName());
if (thisContainer != null) if (thisContainer != null)
{ {
if (thisContainer.length==1) if (thisContainer.length==1)
return new MContainer(getCtx(), thisContainer[0], get_TrxName()); return new MContainer(getCtx(), thisContainer[0], get_TrxName());
} }
return null; return null;
**/ **/
} // getContainer } // getContainer
/** /**
* After Save. * After Save.
* Insert * Insert
* - create / update index * - create / update index
* @param newRecord insert * @param newRecord insert
* @param success save success * @param success save success
* @return true if saved * @return true if saved
*/ */
protected boolean afterSave (boolean newRecord, boolean success) protected boolean afterSave (boolean newRecord, boolean success)
{ {
if (!success) if (!success)
return success; return success;
reIndex(newRecord); reIndex(newRecord);
return success; return success;
} // afterSave } // afterSave
/** /**
* reIndex * reIndex
* @param newRecord * @param newRecord
*/ */
public void reIndex(boolean newRecord) public void reIndex(boolean newRecord)
{ {
int CMWebProjectID = 0; int CMWebProjectID = 0;
if (getParent()!=null) if (getParent()!=null)
CMWebProjectID = getParent().getCM_WebProject_ID(); CMWebProjectID = getParent().getCM_WebProject_ID();
String [] toBeIndexed = new String[3]; String [] toBeIndexed = new String[3];
toBeIndexed[0] = this.getName(); toBeIndexed[0] = this.getName();
toBeIndexed[1] = this.getDescription(); toBeIndexed[1] = this.getDescription();
toBeIndexed[2] = this.getContentHTML(); toBeIndexed[2] = this.getContentHTML();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(), MIndex.reIndex (newRecord, toBeIndexed, getCtx(),
getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated()); getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated());
} // reIndex } // reIndex
} // MContainerElement } // MContainerElement

View File

@ -3,51 +3,115 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
/** /**
* Dunning Level Model * Dunning Level Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MDunningLevel.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: MDunningLevel.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class MDunningLevel extends X_C_DunningLevel public class MDunningLevel extends X_C_DunningLevel
{ {
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MPayment.class);
/** /**
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param C_DunningLevel_ID id * @param C_DunningLevel_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningLevel (Properties ctx, int C_DunningLevel_ID, String trxName) public MDunningLevel (Properties ctx, int C_DunningLevel_ID, String trxName)
{ {
super (ctx, C_DunningLevel_ID, trxName); super (ctx, C_DunningLevel_ID, trxName);
} // MDunningLevel } // MDunningLevel
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningLevel (Properties ctx, ResultSet rs, String trxName) public MDunningLevel (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MDunningLevel } // MDunningLevel
private MDunning m_dunning = null;
/**
* get Parent
* @return Parent Dunning
*/
public MDunning getParent()
{
if (m_dunning==null)
m_dunning = new MDunning(getCtx(), getC_Dunning_ID(), get_TrxName());
return m_dunning;
}
/**
* get Previous Levels
* @return Array of previous DunningLevels
*/
public MDunningLevel[] getPreviousLevels()
{
// Prevent generation if not Sequentially
if (!getParent().isCreateLevelsSequentially ())
return null;
ArrayList<MDunningLevel> list = new ArrayList<MDunningLevel>();
String sql = "SELECT * FROM C_DunningLevel WHERE C_Dunning_ID=? AND DaysAfterDue+DaysBetweenDunning<?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, getParent().get_ID ());
int totalDays = getDaysAfterDue ().intValue ()+getDaysBetweenDunning ();
pstmt.setInt(2, totalDays);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add(new MDunningLevel(getCtx(), rs, get_TrxName()));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
//
MDunningLevel[] retValue = new MDunningLevel[list.size()];
list.toArray(retValue);
return retValue;
}
} // MDunningLevel } // MDunningLevel

View File

@ -3,134 +3,206 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Dunning Run Entry Model * Dunning Run Entry Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MDunningRunEntry.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $ * @version $Id: MDunningRunEntry.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/ */
public class MDunningRunEntry extends X_C_DunningRunEntry public class MDunningRunEntry extends X_C_DunningRunEntry
{ {
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MPayment.class);
/** /**
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param C_DunningRunEntry_ID id * @param C_DunningRunEntry_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningRunEntry (Properties ctx, int C_DunningRunEntry_ID, String trxName) public MDunningRunEntry (Properties ctx, int C_DunningRunEntry_ID, String trxName)
{ {
super (ctx, C_DunningRunEntry_ID, trxName); super (ctx, C_DunningRunEntry_ID, trxName);
if (C_DunningRunEntry_ID == 0) if (C_DunningRunEntry_ID == 0)
{ {
// setC_BPartner_ID (0); // setC_BPartner_ID (0);
// setC_BPartner_Location_ID (0); // setC_BPartner_Location_ID (0);
// setAD_User_ID (0); // setAD_User_ID (0);
// setSalesRep_ID (0); // setSalesRep_ID (0);
// setC_Currency_ID (0); // setC_Currency_ID (0);
setAmt (Env.ZERO); setAmt (Env.ZERO);
setQty (Env.ZERO); setQty (Env.ZERO);
setProcessed (false); setProcessed (false);
} }
} // MDunningRunEntry } // MDunningRunEntry
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningRunEntry (Properties ctx, ResultSet rs, String trxName) public MDunningRunEntry (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MDunningRunEntry } // MDunningRunEntry
/** /**
* Parent Constructor * Parent Constructor
* @param parent parent * @param parent parent
*/ */
public MDunningRunEntry (MDunningRun parent) public MDunningRunEntry (MDunningRun parent)
{ {
this (parent.getCtx(), 0, parent.get_TrxName()); this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent); setClientOrg(parent);
setC_DunningRun_ID(parent.getC_DunningRun_ID()); setC_DunningRun_ID(parent.getC_DunningRun_ID());
m_parent = parent; m_parent = parent;
} // MDunningRunEntry } // MDunningRunEntry
/** Parent */ /** Parent */
private MDunningRun m_parent = null; private MDunningRun m_parent = null;
/** /**
* Set BPartner * Set BPartner
* @param bp partner * @param bp partner
* @param isSOTrx SO * @param isSOTrx SO
*/ */
public void setBPartner (MBPartner bp, boolean isSOTrx) public void setBPartner (MBPartner bp, boolean isSOTrx)
{ {
setC_BPartner_ID(bp.getC_BPartner_ID()); setC_BPartner_ID(bp.getC_BPartner_ID());
MBPartnerLocation[] locations = bp.getLocations(false); MBPartnerLocation[] locations = bp.getLocations(false);
// Location // Location
if (locations.length == 1) if (locations.length == 1)
setC_BPartner_Location_ID (locations[0].getC_BPartner_Location_ID()); setC_BPartner_Location_ID (locations[0].getC_BPartner_Location_ID());
else else
{ {
for (int i = 0; i < locations.length; i++) for (int i = 0; i < locations.length; i++)
{ {
MBPartnerLocation location = locations[i]; MBPartnerLocation location = locations[i];
if ((location.isPayFrom() && isSOTrx) if ((location.isPayFrom() && isSOTrx)
|| (location.isRemitTo() && !isSOTrx)) || (location.isRemitTo() && !isSOTrx))
{ {
setC_BPartner_Location_ID (location.getC_BPartner_Location_ID()); setC_BPartner_Location_ID (location.getC_BPartner_Location_ID());
break; break;
} }
} }
} }
if (getC_BPartner_Location_ID() == 0) if (getC_BPartner_Location_ID() == 0)
{ {
String msg = "@C_BPartner_ID@ " + bp.getName(); String msg = "@C_BPartner_ID@ " + bp.getName();
if (isSOTrx) if (isSOTrx)
msg += " @No@ @IsPayFrom@"; msg += " @No@ @IsPayFrom@";
else else
msg += " @No@ @IsRemitTo@"; msg += " @No@ @IsRemitTo@";
throw new IllegalArgumentException (msg); throw new IllegalArgumentException (msg);
} }
// User with location // User with location
MUser[] users = MUser.getOfBPartner(getCtx(), bp.getC_BPartner_ID()); MUser[] users = MUser.getOfBPartner(getCtx(), bp.getC_BPartner_ID());
if (users.length == 1) if (users.length == 1)
setAD_User_ID (users[0].getAD_User_ID()); setAD_User_ID (users[0].getAD_User_ID());
else else
{ {
for (int i = 0; i < users.length; i++) for (int i = 0; i < users.length; i++)
{ {
MUser user = users[i]; MUser user = users[i];
if (user.getC_BPartner_Location_ID() == getC_BPartner_Location_ID()) if (user.getC_BPartner_Location_ID() == getC_BPartner_Location_ID())
{ {
setAD_User_ID (users[i].getAD_User_ID()); setAD_User_ID (users[i].getAD_User_ID());
break; break;
} }
} }
} }
// //
int SalesRep_ID = bp.getSalesRep_ID(); int SalesRep_ID = bp.getSalesRep_ID();
if (SalesRep_ID != 0) if (SalesRep_ID != 0)
setSalesRep_ID (SalesRep_ID); setSalesRep_ID (SalesRep_ID);
} // setBPartner } // setBPartner
/**
* get Lines
* @return Array of all lines for this Run
*/
public MDunningRunLine[] getLines()
{
ArrayList<MDunningRunLine> list = new ArrayList<MDunningRunLine>();
String sql = "SELECT * FROM C_DunningRunLine WHERE C_DunningRunEntry_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, get_ID ());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add(new MDunningRunLine(getCtx(), rs, get_TrxName()));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
//
MDunningRunLine[] retValue = new MDunningRunLine[list.size()];
list.toArray(retValue);
return retValue;
}
protected boolean beforeSave (boolean newRecord)
{
// Set Amt
if (isProcessed ())
{
MDunningRunLine[] theseLines = getLines();
for (int i=0;i<theseLines.length;i++)
{
theseLines[i].setProcessed (true);
theseLines[i].save (get_TrxName());
}
if (m_parent.getLevel ().isSetCreditStop () || m_parent.getLevel ().isSetPaymentTerm ())
{
MBPartner thisBPartner = MBPartner.get (getCtx(), getC_BPartner_ID());
if (m_parent.getLevel ().isSetCreditStop ())
thisBPartner.setSOCreditStatus (X_C_BPartner.SOCREDITSTATUS_CreditStop);
if (m_parent.getLevel ().isSetPaymentTerm ())
thisBPartner.setC_PaymentTerm_ID (m_parent.getLevel().getC_PaymentTerm_ID ());
thisBPartner.save ();
}
}
return true;
} // beforeSave
} // MDunningRunEntry } // MDunningRunEntry

View File

@ -3,304 +3,339 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Dunning Run Line Model * Dunning Run Line Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MDunningRunLine.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: MDunningRunLine.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class MDunningRunLine extends X_C_DunningRunLine public class MDunningRunLine extends X_C_DunningRunLine
{ {
/** /**
* Standarc Constructor * Standarc Constructor
* @param ctx ctx * @param ctx ctx
* @param C_DunningRunLine_ID id * @param C_DunningRunLine_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningRunLine (Properties ctx, int C_DunningRunLine_ID, String trxName) public MDunningRunLine (Properties ctx, int C_DunningRunLine_ID, String trxName)
{ {
super (ctx, C_DunningRunLine_ID, trxName); super (ctx, C_DunningRunLine_ID, trxName);
if (C_DunningRunLine_ID == 0) if (C_DunningRunLine_ID == 0)
{ {
setAmt (Env.ZERO); setAmt (Env.ZERO);
setOpenAmt(Env.ZERO); setOpenAmt(Env.ZERO);
setConvertedAmt (Env.ZERO); setConvertedAmt (Env.ZERO);
setFeeAmt (Env.ZERO); setFeeAmt (Env.ZERO);
setInterestAmt (Env.ZERO); setInterestAmt (Env.ZERO);
setTotalAmt (Env.ZERO); setTotalAmt (Env.ZERO);
setDaysDue (0); setDaysDue (0);
setTimesDunned (0); setTimesDunned (0);
setIsInDispute(false); setIsInDispute(false);
setProcessed (false); setProcessed (false);
} }
} // MDunningRunLine } // MDunningRunLine
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MDunningRunLine (Properties ctx, ResultSet rs, String trxName) public MDunningRunLine (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MDunningRunLine } // MDunningRunLine
/** /**
* Parent Constructor * Parent Constructor
* @param parent parent * @param parent parent
*/ */
public MDunningRunLine (MDunningRunEntry parent) public MDunningRunLine (MDunningRunEntry parent)
{ {
this(parent.getCtx(), 0, parent.get_TrxName()); this(parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent); setClientOrg(parent);
setC_DunningRunEntry_ID(parent.getC_DunningRunEntry_ID()); setC_DunningRunEntry_ID(parent.getC_DunningRunEntry_ID());
// //
m_parent = parent; m_parent = parent;
m_C_CurrencyTo_ID = parent.getC_Currency_ID(); m_C_CurrencyTo_ID = parent.getC_Currency_ID();
} // MDunningRunLine } // MDunningRunLine
private MDunningRunEntry m_parent = null; private MDunningRunEntry m_parent = null;
private MInvoice m_invoice = null; private MInvoice m_invoice = null;
private MPayment m_payment = null; private MPayment m_payment = null;
private int m_C_CurrencyFrom_ID = 0; private int m_C_CurrencyFrom_ID = 0;
private int m_C_CurrencyTo_ID = 0; private int m_C_CurrencyTo_ID = 0;
/** /**
* Get Parent * Get Parent
* @return parent * @return parent
*/ */
public MDunningRunEntry getParent() public MDunningRunEntry getParent()
{ {
if (m_parent == null) if (m_parent == null)
m_parent = new MDunningRunEntry (getCtx(), getC_DunningRunEntry_ID(), get_TrxName()); m_parent = new MDunningRunEntry (getCtx(), getC_DunningRunEntry_ID(), get_TrxName());
return m_parent; return m_parent;
} // getParent } // getParent
/** /**
* Get Invoice * Get Invoice
* @return Returns the invoice. * @return Returns the invoice.
*/ */
public MInvoice getInvoice () public MInvoice getInvoice ()
{ {
if (getC_Invoice_ID() == 0) if (getC_Invoice_ID() == 0)
m_invoice = null; m_invoice = null;
else if (m_invoice == null) else if (m_invoice == null)
m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName()); m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName());
return m_invoice; return m_invoice;
} // getInvoice } // getInvoice
/** /**
* Set Invoice * Set Invoice
* @param invoice The invoice to set. * @param invoice The invoice to set.
*/ */
public void setInvoice (MInvoice invoice) public void setInvoice (MInvoice invoice)
{ {
m_invoice = invoice; m_invoice = invoice;
if (invoice != null) if (invoice != null)
{ {
m_C_CurrencyFrom_ID = invoice.getC_Currency_ID(); m_C_CurrencyFrom_ID = invoice.getC_Currency_ID();
setAmt(invoice.getGrandTotal()); setAmt(invoice.getGrandTotal());
setOpenAmt(getAmt()); // not correct setOpenAmt(getAmt()); // not correct
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(), setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID())); getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
} }
else else
{ {
m_C_CurrencyFrom_ID = 0; m_C_CurrencyFrom_ID = 0;
setAmt(Env.ZERO); setAmt(Env.ZERO);
setOpenAmt(Env.ZERO); setOpenAmt(Env.ZERO);
setConvertedAmt(Env.ZERO); setConvertedAmt(Env.ZERO);
} }
} // setInvoice } // setInvoice
/** /**
* Set Invoice * Set Invoice
* @param C_Invoice_ID * @param C_Invoice_ID
* @param C_Currency_ID * @param C_Currency_ID
* @param GrandTotal * @param GrandTotal
* @param Open * @param Open
* @param FeeAmount
* @param DaysDue * @param DaysDue
* @param IsInDispute * @param IsInDispute
* @param TimesDunned * @param TimesDunned
* @param DaysAfterLast not used * @param DaysAfterLast not used
*/ */
public void setInvoice (int C_Invoice_ID, int C_Currency_ID, public void setInvoice (int C_Invoice_ID, int C_Currency_ID,
BigDecimal GrandTotal, BigDecimal Open, BigDecimal GrandTotal, BigDecimal Open,
BigDecimal FeeAmount,
int DaysDue, boolean IsInDispute, int DaysDue, boolean IsInDispute,
int TimesDunned, int DaysAfterLast) int TimesDunned, int DaysAfterLast)
{ {
setC_Invoice_ID(C_Invoice_ID); setC_Invoice_ID(C_Invoice_ID);
m_C_CurrencyFrom_ID = C_Currency_ID; m_C_CurrencyFrom_ID = C_Currency_ID;
setAmt (GrandTotal); setAmt (GrandTotal);
setOpenAmt (Open); setOpenAmt (Open);
setFeeAmt (FeeAmount);
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(), setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
C_Currency_ID, getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID())); C_Currency_ID, getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
setIsInDispute(IsInDispute); setIsInDispute(IsInDispute);
setDaysDue(DaysDue); setDaysDue(DaysDue);
setTimesDunned(TimesDunned); setTimesDunned(TimesDunned);
} // setInvoice } // setInvoice
/**
* Set Fee
* @param C_Currency_ID
* @param FeeAmount
*/
public void setFee (int C_Currency_ID,
BigDecimal FeeAmount)
{
m_C_CurrencyFrom_ID = C_Currency_ID;
setAmt (FeeAmount);
setOpenAmt (FeeAmount);
setFeeAmt (FeeAmount);
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
C_Currency_ID, getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
} // setInvoice
/** /**
* Get Payment * Get Payment
* @return Returns the payment. * @return Returns the payment.
*/ */
public MPayment getPayment () public MPayment getPayment ()
{ {
if (getC_Payment_ID() == 0) if (getC_Payment_ID() == 0)
m_payment = null; m_payment = null;
else if (m_payment == null) else if (m_payment == null)
m_payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName()); m_payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName());
return m_payment; return m_payment;
} // getPayment } // getPayment
/** /**
* Set Payment * Set Payment
* *
public void setPayment (MPayment payment) public void setPayment (MPayment payment)
{ {
m_payment = payment; m_payment = payment;
if (payment != null) if (payment != null)
{ {
m_C_CurrencyFrom_ID = payment.getC_Currency_ID(); m_C_CurrencyFrom_ID = payment.getC_Currency_ID();
setAmt(payment.getPayAmt()); // need to reverse setAmt(payment.getPayAmt()); // need to reverse
setOpenAmt(getAmt()); // not correct setOpenAmt(getAmt()); // not correct
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(), setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID())); getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
} }
else else
{ {
m_C_CurrencyFrom_ID = 0; m_C_CurrencyFrom_ID = 0;
setAmt(Env.ZERO); setAmt(Env.ZERO);
setConvertedAmt(Env.ZERO); setConvertedAmt(Env.ZERO);
} }
} // setPayment } // setPayment
/** /**
* Set Payment * Set Payment
* @param C_Payment_ID * @param C_Payment_ID
* @param C_Currency_ID * @param C_Currency_ID
* @param PayAmt * @param PayAmt
* @param OpenAmt * @param OpenAmt
*/ */
public void setPayment (int C_Payment_ID, int C_Currency_ID, public void setPayment (int C_Payment_ID, int C_Currency_ID,
BigDecimal PayAmt, BigDecimal OpenAmt) BigDecimal PayAmt, BigDecimal OpenAmt)
{ {
setC_Payment_ID(C_Payment_ID); setC_Payment_ID(C_Payment_ID);
m_C_CurrencyFrom_ID = C_Currency_ID; m_C_CurrencyFrom_ID = C_Currency_ID;
setAmt (PayAmt); setAmt (PayAmt);
setOpenAmt (OpenAmt); setOpenAmt (OpenAmt);
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(), setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
C_Currency_ID, getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID())); C_Currency_ID, getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
} // setPayment } // setPayment
/** /**
* Get Currency From (Invoice/Payment) * Get Currency From (Invoice/Payment)
* @return Returns the Currency From * @return Returns the Currency From
*/ */
public int getC_CurrencyFrom_ID () public int getC_CurrencyFrom_ID ()
{ {
if (m_C_CurrencyFrom_ID == 0) if (m_C_CurrencyFrom_ID == 0)
{ {
if (getC_Invoice_ID() != 0) if (getC_Invoice_ID() != 0)
m_C_CurrencyFrom_ID = getInvoice().getC_Currency_ID(); m_C_CurrencyFrom_ID = getInvoice().getC_Currency_ID();
else if (getC_Payment_ID() != 0) else if (getC_Payment_ID() != 0)
m_C_CurrencyFrom_ID = getPayment().getC_Currency_ID(); m_C_CurrencyFrom_ID = getPayment().getC_Currency_ID();
} }
return m_C_CurrencyFrom_ID; return m_C_CurrencyFrom_ID;
} // getC_CurrencyFrom_ID } // getC_CurrencyFrom_ID
/** /**
* Get Currency To from Parent * Get Currency To from Parent
* @return Returns the Currency To * @return Returns the Currency To
*/ */
public int getC_CurrencyTo_ID () public int getC_CurrencyTo_ID ()
{ {
if (m_C_CurrencyTo_ID == 0) if (m_C_CurrencyTo_ID == 0)
m_C_CurrencyTo_ID = getParent().getC_Currency_ID(); m_C_CurrencyTo_ID = getParent().getC_Currency_ID();
return m_C_CurrencyTo_ID; return m_C_CurrencyTo_ID;
} // getC_CurrencyTo_ID } // getC_CurrencyTo_ID
/** /**
* Before Save * Before Save
* @param newRecord new * @param newRecord new
* @return true * @return true
*/ */
protected boolean beforeSave (boolean newRecord) protected boolean beforeSave (boolean newRecord)
{ {
// Set Amt // Set Amt
if (getC_Invoice_ID() == 0 && getC_Payment_ID() == 0) if (getC_Invoice_ID() == 0 && getC_Payment_ID() == 0)
{ {
setAmt(Env.ZERO); setAmt(Env.ZERO);
setOpenAmt(Env.ZERO); setOpenAmt(Env.ZERO);
} }
// Converted Amt // Converted Amt
if (Env.ZERO.compareTo(getOpenAmt()) == 0) if (Env.ZERO.compareTo(getOpenAmt()) == 0)
setConvertedAmt (Env.ZERO); setConvertedAmt (Env.ZERO);
else if (Env.ZERO.compareTo(getConvertedAmt()) == 0) else if (Env.ZERO.compareTo(getConvertedAmt()) == 0)
setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(), setConvertedAmt (MConversionRate.convert(getCtx(), getOpenAmt(),
getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID())); getC_CurrencyFrom_ID(), getC_CurrencyTo_ID(), getAD_Client_ID(), getAD_Org_ID()));
// Total // Total
setTotalAmt(getConvertedAmt().add(getFeeAmt()).add(getInterestAmt())); setTotalAmt(getConvertedAmt().add(getFeeAmt()).add(getInterestAmt()));
// Reset Collection Status only if null
if (getInvoice().getInvoiceCollectionType ()==null)
{
if (m_invoice!=null)
{
m_invoice.setInvoiceCollectionType (X_C_Invoice.INVOICECOLLECTIONTYPE_Dunning);
m_invoice.save ();
}
}
// //
return true; return true;
} // beforeSave } // beforeSave
/** /**
* After Save * After Save
* @param newRecord new * @param newRecord new
* @param success success * @param success success
* @return success * @return success
*/ */
protected boolean afterSave (boolean newRecord, boolean success) protected boolean afterSave (boolean newRecord, boolean success)
{ {
updateEntry(); updateEntry();
return success; return success;
} // afterSave } // afterSave
/** /**
* After Delete * After Delete
* @param success success * @param success success
* @return success * @return success
*/ */
protected boolean afterDelete (boolean success) protected boolean afterDelete (boolean success)
{ {
updateEntry(); updateEntry();
return success; return success;
} // afterDelete } // afterDelete
/** /**
* Update Entry. * Update Entry.
* Calculate/update Amt/Qty * Calculate/update Amt/Qty
*/ */
private void updateEntry() private void updateEntry()
{ {
// we do not count the fee line as an item, but it sum it up.
String sql = "UPDATE C_DunningRunEntry e " String sql = "UPDATE C_DunningRunEntry e "
+ "SET (Amt,Qty)=(SELECT SUM(Amt),COUNT(*) FROM C_DunningRunLine l " + "SET Amt=(SELECT SUM(ConvertedAmt)+SUM(FeeAmt)"
+ "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID) " + " FROM C_DunningRunLine l "
+ "WHERE C_DunningRunEntry_ID=" + getC_DunningRunEntry_ID(); + "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID), "
+ "QTY=(SELECT COUNT(*)"
+ " FROM C_DunningRunLine l "
+ "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID "
+ " AND (NOT C_Invoice_ID IS NULL OR NOT C_Payment_ID IS NULL))"
+ " WHERE C_DunningRunEntry_ID=" + getC_DunningRunEntry_ID();
DB.executeUpdate(sql, get_TrxName()); DB.executeUpdate(sql, get_TrxName());
} // updateEntry } // updateEntry
} // MDunningRunLine } // MDunningRunLine

View File

@ -3,164 +3,224 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Interest Area. * Interest Area.
* Note: if model is changed, update * Note: if model is changed, update
* org.compiere.wstore.Info.getInterests() * org.compiere.wstore.Info.getInterests()
* manually * manually
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MInterestArea.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $ * @version $Id: MInterestArea.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/ */
public class MInterestArea extends X_R_InterestArea public class MInterestArea extends X_R_InterestArea
{ {
/**
* Get all active interest areas
* @param ctx context
* @return interest areas
*/
public static MInterestArea[] getAll (Properties ctx)
{
ArrayList<MInterestArea> list = new ArrayList<MInterestArea>();
String sql = "SELECT * FROM R_InterestArea WHERE IsActive='Y'";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
MInterestArea ia = new MInterestArea (ctx, rs, null);
list.add (ia);
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MInterestArea[] retValue = new MInterestArea[list.size ()];
list.toArray (retValue);
return retValue;
} // getAll
/** /**
* Get MInterestArea from Cache * Get MInterestArea from Cache
* @param ctx context * @param ctx context
* @param R_InterestArea_ID id * @param R_InterestArea_ID id
* @return MInterestArea * @return MInterestArea
*/ */
public static MInterestArea get (Properties ctx, int R_InterestArea_ID) public static MInterestArea get (Properties ctx, int R_InterestArea_ID)
{ {
Integer key = new Integer (R_InterestArea_ID); Integer key = new Integer (R_InterestArea_ID);
MInterestArea retValue = (MInterestArea) s_cache.get (key); MInterestArea retValue = (MInterestArea) s_cache.get (key);
if (retValue != null) if (retValue != null)
return retValue; return retValue;
retValue = new MInterestArea (ctx, R_InterestArea_ID, null); retValue = new MInterestArea (ctx, R_InterestArea_ID, null);
if (retValue.get_ID () != 0) if (retValue.get_ID () != 0)
s_cache.put (key, retValue); s_cache.put (key, retValue);
return retValue; return retValue;
} // get } // get
/** Cache */ /** Cache */
private static CCache<Integer,MInterestArea> s_cache = new CCache<Integer,MInterestArea>("R_InterestArea", 5); private static CCache<Integer,MInterestArea> s_cache =
new CCache<Integer,MInterestArea>("R_InterestArea", 5);
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MInterestArea.class);
/** /**
* Constructor * Constructor
* @param ctx context * @param ctx context
* @param R_InterestArea_ID interest area * @param R_InterestArea_ID interest area
* @param trxName transaction * @param trxName transaction
*/ */
public MInterestArea (Properties ctx, int R_InterestArea_ID, String trxName) public MInterestArea (Properties ctx, int R_InterestArea_ID, String trxName)
{ {
super (ctx, R_InterestArea_ID, trxName); super (ctx, R_InterestArea_ID, trxName);
if (R_InterestArea_ID == 0) if (R_InterestArea_ID == 0)
{ {
// setName (null); // setName (null);
// setR_InterestArea_ID (0); // setR_InterestArea_ID (0);
setIsSelfService (false);
} }
} // MInterestArea } // MInterestArea
/** /**
* Loader Constructor * Loader Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MInterestArea (Properties ctx, ResultSet rs, String trxName) public MInterestArea (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MInterestArea } // MInterestArea
/**
* Get Value
* @return value
*/
public String getValue()
{
String s = super.getValue ();
if (s != null && s.length () > 0)
return s;
return super.getName();
} // getValue
/** /**
* String representation * String representation
* @return info * @return info
*/ */
public String toString () public String toString ()
{ {
StringBuffer sb = new StringBuffer ("MInterestArea[") StringBuffer sb = new StringBuffer ("MInterestArea[")
.append (get_ID()).append(" - ").append(getName()) .append (get_ID()).append(" - ").append(getName())
.append ("]"); .append ("]");
return sb.toString (); return sb.toString ();
} } // toString
/*************************************************************************/ /*************************************************************************/
private int m_AD_User_ID = -1; private int m_AD_User_ID = -1;
private MContactInterest m_ci = null; private MContactInterest m_ci = null;
/** /**
* Set Subscription info "constructor". * Set Subscription info "constructor".
* Create inactive Subscription * Create inactive Subscription
* @param AD_User_ID contact * @param AD_User_ID contact
*/ */
public void setSubscriptionInfo (int AD_User_ID) public void setSubscriptionInfo (int AD_User_ID)
{ {
m_AD_User_ID = AD_User_ID; m_AD_User_ID = AD_User_ID;
m_ci = MContactInterest.get(getCtx(), getR_InterestArea_ID(), AD_User_ID, m_ci = MContactInterest.get(getCtx(), getR_InterestArea_ID(), AD_User_ID,
false, get_TrxName()); false, get_TrxName());
} // setSubscription } // setSubscription
/** /**
* Set AD_User_ID * Set AD_User_ID
* @param AD_User_ID user * @param AD_User_ID user
*/ */
public void setAD_User_ID (int AD_User_ID) public void setAD_User_ID (int AD_User_ID)
{ {
m_AD_User_ID = AD_User_ID; m_AD_User_ID = AD_User_ID;
} }
/** /**
* Get AD_User_ID * Get AD_User_ID
* @return user * @return user
*/ */
public int getAD_User_ID () public int getAD_User_ID ()
{ {
return m_AD_User_ID; return m_AD_User_ID;
} }
/** /**
* Get Subscribe Date * Get Subscribe Date
* @return subscribe date * @return subscribe date
*/ */
public Timestamp getSubscribeDate () public Timestamp getSubscribeDate ()
{ {
if (m_ci != null) if (m_ci != null)
return m_ci.getSubscribeDate(); return m_ci.getSubscribeDate();
return null; return null;
} }
/** /**
* Get Opt Out Date * Get Opt Out Date
* @return opt-out date * @return opt-out date
*/ */
public Timestamp getOptOutDate () public Timestamp getOptOutDate ()
{ {
if (m_ci != null) if (m_ci != null)
return m_ci.getOptOutDate(); return m_ci.getOptOutDate();
return null; return null;
} }
/** /**
* Is Subscribed * Is Subscribed
* @return true if sunscribed * @return true if sunscribed
*/ */
public boolean isSubscribed() public boolean isSubscribed()
{ {
if (m_AD_User_ID <= 0 || m_ci == null) if (m_AD_User_ID <= 0 || m_ci == null)
return false; return false;
// We have a BPartner Contact // We have a BPartner Contact
return m_ci.isSubscribed(); return m_ci.isSubscribed();
} // isSubscribed } // isSubscribed
} // MInterestArea } // MInterestArea

View File

@ -3,413 +3,413 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Physical Inventory Line Model * Physical Inventory Line Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MInventoryLine.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: MInventoryLine.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class MInventoryLine extends X_M_InventoryLine public class MInventoryLine extends X_M_InventoryLine
{ {
/** /**
* Get Inventory Line with parameters * Get Inventory Line with parameters
* @param inventory inventory * @param inventory inventory
* @param M_Locator_ID locator * @param M_Locator_ID locator
* @param M_Product_ID product * @param M_Product_ID product
* @param M_AttributeSetInstance_ID asi * @param M_AttributeSetInstance_ID asi
* @return line or null * @return line or null
*/ */
public static MInventoryLine get (MInventory inventory, public static MInventoryLine get (MInventory inventory,
int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID) int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID)
{ {
MInventoryLine retValue = null; MInventoryLine retValue = null;
String sql = "SELECT * FROM M_InventoryLine " String sql = "SELECT * FROM M_InventoryLine "
+ "WHERE M_Inventory_ID=? AND M_Locator_ID=?" + "WHERE M_Inventory_ID=? AND M_Locator_ID=?"
+ " AND M_Product_ID=? AND M_AttributeSetInstance_ID=?"; + " AND M_Product_ID=? AND M_AttributeSetInstance_ID=?";
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, inventory.get_TrxName()); pstmt = DB.prepareStatement (sql, inventory.get_TrxName());
pstmt.setInt (1, inventory.getM_Inventory_ID()); pstmt.setInt (1, inventory.getM_Inventory_ID());
pstmt.setInt(2, M_Locator_ID); pstmt.setInt(2, M_Locator_ID);
pstmt.setInt(3, M_Product_ID); pstmt.setInt(3, M_Product_ID);
pstmt.setInt(4, M_AttributeSetInstance_ID); pstmt.setInt(4, M_AttributeSetInstance_ID);
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
if (rs.next ()) if (rs.next ())
retValue = new MInventoryLine (inventory.getCtx(), rs, inventory.get_TrxName()); retValue = new MInventoryLine (inventory.getCtx(), rs, inventory.get_TrxName());
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
s_log.log (Level.SEVERE, sql, e); s_log.log (Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
return retValue; return retValue;
} // get } // get
/** Logger */ /** Logger */
private static CLogger s_log = CLogger.getCLogger (MInventoryLine.class); private static CLogger s_log = CLogger.getCLogger (MInventoryLine.class);
/************************************************************************** /**************************************************************************
* Default Constructor * Default Constructor
* @param ctx context * @param ctx context
* @param M_InventoryLine_ID line * @param M_InventoryLine_ID line
* @param trxName transaction * @param trxName transaction
*/ */
public MInventoryLine (Properties ctx, int M_InventoryLine_ID, String trxName) public MInventoryLine (Properties ctx, int M_InventoryLine_ID, String trxName)
{ {
super (ctx, M_InventoryLine_ID, trxName); super (ctx, M_InventoryLine_ID, trxName);
if (M_InventoryLine_ID == 0) if (M_InventoryLine_ID == 0)
{ {
// setM_Inventory_ID (0); // Parent // setM_Inventory_ID (0); // Parent
// setM_InventoryLine_ID (0); // PK // setM_InventoryLine_ID (0); // PK
// setM_Locator_ID (0); // FK // setM_Locator_ID (0); // FK
setLine(0); setLine(0);
// setM_Product_ID (0); // FK // setM_Product_ID (0); // FK
setM_AttributeSetInstance_ID(0); // FK setM_AttributeSetInstance_ID(0); // FK
setInventoryType (INVENTORYTYPE_InventoryDifference); setInventoryType (INVENTORYTYPE_InventoryDifference);
setQtyBook (Env.ZERO); setQtyBook (Env.ZERO);
setQtyCount (Env.ZERO); setQtyCount (Env.ZERO);
setProcessed(false); setProcessed(false);
} }
} // MInventoryLine } // MInventoryLine
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MInventoryLine (Properties ctx, ResultSet rs, String trxName) public MInventoryLine (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MInventoryLine } // MInventoryLine
/** /**
* Detail Constructor. * Detail Constructor.
* Locator/Product/AttributeSetInstance must be unique * Locator/Product/AttributeSetInstance must be unique
* @param inventory parent * @param inventory parent
* @param M_Locator_ID locator * @param M_Locator_ID locator
* @param M_Product_ID product * @param M_Product_ID product
* @param M_AttributeSetInstance_ID instance * @param M_AttributeSetInstance_ID instance
* @param QtyBook book value * @param QtyBook book value
* @param QtyCount count value * @param QtyCount count value
*/ */
public MInventoryLine (MInventory inventory, public MInventoryLine (MInventory inventory,
int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID, int M_Locator_ID, int M_Product_ID, int M_AttributeSetInstance_ID,
BigDecimal QtyBook, BigDecimal QtyCount) BigDecimal QtyBook, BigDecimal QtyCount)
{ {
this (inventory.getCtx(), 0, inventory.get_TrxName()); this (inventory.getCtx(), 0, inventory.get_TrxName());
if (inventory.get_ID() == 0) if (inventory.get_ID() == 0)
throw new IllegalArgumentException("Header not saved"); throw new IllegalArgumentException("Header not saved");
m_parent = inventory; m_parent = inventory;
setM_Inventory_ID (inventory.getM_Inventory_ID()); // Parent setM_Inventory_ID (inventory.getM_Inventory_ID()); // Parent
setClientOrg (inventory.getAD_Client_ID(), inventory.getAD_Org_ID()); setClientOrg (inventory.getAD_Client_ID(), inventory.getAD_Org_ID());
setM_Locator_ID (M_Locator_ID); // FK setM_Locator_ID (M_Locator_ID); // FK
setM_Product_ID (M_Product_ID); // FK setM_Product_ID (M_Product_ID); // FK
setM_AttributeSetInstance_ID (M_AttributeSetInstance_ID); setM_AttributeSetInstance_ID (M_AttributeSetInstance_ID);
// //
if (QtyBook != null) if (QtyBook != null)
setQtyBook (QtyBook); setQtyBook (QtyBook);
if (QtyCount != null && QtyCount.signum() != 0) if (QtyCount != null && QtyCount.signum() != 0)
setQtyCount (QtyCount); setQtyCount (QtyCount);
m_isManualEntry = false; m_isManualEntry = false;
} // MInventoryLine } // MInventoryLine
/** Manually created */ /** Manually created */
private boolean m_isManualEntry = true; private boolean m_isManualEntry = true;
/** Parent */ /** Parent */
private MInventory m_parent = null; private MInventory m_parent = null;
/** Product */ /** Product */
private MProduct m_product = null; private MProduct m_product = null;
/** /**
* Get Qty Book * Get Qty Book
* @return Qty Book * @return Qty Book
*/ */
public BigDecimal getQtyBook () public BigDecimal getQtyBook ()
{ {
BigDecimal bd = super.getQtyBook (); BigDecimal bd = super.getQtyBook ();
if (bd == null) if (bd == null)
bd = Env.ZERO; bd = Env.ZERO;
return bd; return bd;
} // getQtyBook } // getQtyBook
/** /**
* Get Qty Count * Get Qty Count
* @return Qty Count * @return Qty Count
*/ */
public BigDecimal getQtyCount () public BigDecimal getQtyCount ()
{ {
BigDecimal bd = super.getQtyCount(); BigDecimal bd = super.getQtyCount();
if (bd == null) if (bd == null)
bd = Env.ZERO; bd = Env.ZERO;
return bd; return bd;
} // getQtyBook } // getQtyBook
/** /**
* Get Product * Get Product
* @return product or null if not defined * @return product or null if not defined
*/ */
public MProduct getProduct() public MProduct getProduct()
{ {
int M_Product_ID = getM_Product_ID(); int M_Product_ID = getM_Product_ID();
if (M_Product_ID == 0) if (M_Product_ID == 0)
return null; return null;
if (m_product != null && m_product.getM_Product_ID() != M_Product_ID) if (m_product != null && m_product.getM_Product_ID() != M_Product_ID)
m_product = null; // reset m_product = null; // reset
if (m_product == null) if (m_product == null)
m_product = MProduct.get(getCtx(), M_Product_ID); m_product = MProduct.get(getCtx(), M_Product_ID);
return m_product; return m_product;
} // getProduct } // getProduct
/** /**
* Set Count Qty - enforce UOM * Set Count Qty - enforce UOM
* @param QtyCount qty * @param QtyCount qty
*/ */
public void setQtyCount (BigDecimal QtyCount) public void setQtyCount (BigDecimal QtyCount)
{ {
if (QtyCount != null) if (QtyCount != null)
{ {
MProduct product = getProduct(); MProduct product = getProduct();
if (product != null) if (product != null)
{ {
int precision = product.getUOMPrecision(); int precision = product.getUOMPrecision();
QtyCount = QtyCount.setScale(precision, BigDecimal.ROUND_HALF_UP); QtyCount = QtyCount.setScale(precision, BigDecimal.ROUND_HALF_UP);
} }
} }
super.setQtyCount(QtyCount); super.setQtyCount(QtyCount);
} // setQtyCount } // setQtyCount
/** /**
* Set Internal Use Qty - enforce UOM * Set Internal Use Qty - enforce UOM
* @param QtyInternalUse qty * @param QtyInternalUse qty
*/ */
public void setQtyInternalUse (BigDecimal QtyInternalUse) public void setQtyInternalUse (BigDecimal QtyInternalUse)
{ {
if (QtyInternalUse != null) if (QtyInternalUse != null)
{ {
MProduct product = getProduct(); MProduct product = getProduct();
if (product != null) if (product != null)
{ {
int precision = product.getUOMPrecision(); int precision = product.getUOMPrecision();
QtyInternalUse = QtyInternalUse.setScale(precision, BigDecimal.ROUND_HALF_UP); QtyInternalUse = QtyInternalUse.setScale(precision, BigDecimal.ROUND_HALF_UP);
} }
} }
super.setQtyInternalUse(QtyInternalUse); super.setQtyInternalUse(QtyInternalUse);
} // setQtyInternalUse } // setQtyInternalUse
/** /**
* Add to Description * Add to Description
* @param description text * @param description text
*/ */
public void addDescription (String description) public void addDescription (String description)
{ {
String desc = getDescription(); String desc = getDescription();
if (desc == null) if (desc == null)
setDescription(description); setDescription(description);
else else
setDescription(desc + " | " + description); setDescription(desc + " | " + description);
} // addDescription } // addDescription
/** /**
* Get Parent * Get Parent
* @param parent parent * @param parent parent
*/ */
protected void setParent(MInventory parent) protected void setParent(MInventory parent)
{ {
m_parent = parent; m_parent = parent;
} // setParent } // setParent
/** /**
* Get Parent * Get Parent
* @return parent * @return parent
*/ */
private MInventory getParent() public MInventory getParent()
{ {
if (m_parent == null) if (m_parent == null)
m_parent = new MInventory (getCtx(), getM_Inventory_ID(), get_TrxName()); m_parent = new MInventory (getCtx(), getM_Inventory_ID(), get_TrxName());
return m_parent; return m_parent;
} // getParent } // getParent
/** /**
* String Representation * String Representation
* @return info * @return info
*/ */
public String toString () public String toString ()
{ {
StringBuffer sb = new StringBuffer ("MInventoryLine["); StringBuffer sb = new StringBuffer ("MInventoryLine[");
sb.append (get_ID()) sb.append (get_ID())
.append("-M_Product_ID=").append (getM_Product_ID()) .append("-M_Product_ID=").append (getM_Product_ID())
.append(",QtyCount=").append(getQtyCount()) .append(",QtyCount=").append(getQtyCount())
.append(",QtyInternalUse=").append(getQtyInternalUse()) .append(",QtyInternalUse=").append(getQtyInternalUse())
.append(",QtyBook=").append(getQtyBook()) .append(",QtyBook=").append(getQtyBook())
.append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID()) .append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID())
.append("]"); .append("]");
return sb.toString (); return sb.toString ();
} // toString } // toString
/** /**
* Before Save * Before Save
* @param newRecord new * @param newRecord new
* @return true if can be saved * @return true if can be saved
*/ */
protected boolean beforeSave (boolean newRecord) protected boolean beforeSave (boolean newRecord)
{ {
if (newRecord && m_isManualEntry) if (newRecord && m_isManualEntry)
{ {
// Product requires ASI // Product requires ASI
if (getM_AttributeSetInstance_ID() == 0) if (getM_AttributeSetInstance_ID() == 0)
{ {
MProduct product = MProduct.get(getCtx(), getM_Product_ID()); MProduct product = MProduct.get(getCtx(), getM_Product_ID());
if (product.getM_AttributeSet_ID() != 0) if (product.getM_AttributeSet_ID() != 0)
{ {
MAttributeSet mas = MAttributeSet.get(getCtx(), product.getM_AttributeSet_ID()); MAttributeSet mas = MAttributeSet.get(getCtx(), product.getM_AttributeSet_ID());
if (mas.isInstanceAttribute() if (mas.isInstanceAttribute()
&& (mas.isMandatory() || mas.isMandatoryAlways())) && (mas.isMandatory() || mas.isMandatoryAlways()))
{ {
log.saveError("FillMandatory", Msg.getElement(getCtx(), "M_AttributeSetInstance_ID")); log.saveError("FillMandatory", Msg.getElement(getCtx(), "M_AttributeSetInstance_ID"));
return false; return false;
} }
} }
} // No ASI } // No ASI
} // new or manual } // new or manual
// Set Line No // Set Line No
if (getLine() == 0) if (getLine() == 0)
{ {
String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_InventoryLine WHERE M_Inventory_ID=?"; String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_InventoryLine WHERE M_Inventory_ID=?";
int ii = DB.getSQLValue (get_TrxName(), sql, getM_Inventory_ID()); int ii = DB.getSQLValue (get_TrxName(), sql, getM_Inventory_ID());
setLine (ii); setLine (ii);
} }
// Enforce Qty UOM // Enforce Qty UOM
if (newRecord || is_ValueChanged("QtyCount")) if (newRecord || is_ValueChanged("QtyCount"))
setQtyCount(getQtyCount()); setQtyCount(getQtyCount());
if (newRecord || is_ValueChanged("QtyInternalUse")) if (newRecord || is_ValueChanged("QtyInternalUse"))
setQtyInternalUse(getQtyInternalUse()); setQtyInternalUse(getQtyInternalUse());
// InternalUse Inventory // InternalUse Inventory
if (getQtyInternalUse().signum() != 0) if (getQtyInternalUse().signum() != 0)
{ {
if (!INVENTORYTYPE_ChargeAccount.equals(getInventoryType())) if (!INVENTORYTYPE_ChargeAccount.equals(getInventoryType()))
setInventoryType(INVENTORYTYPE_ChargeAccount); setInventoryType(INVENTORYTYPE_ChargeAccount);
// //
if (getC_Charge_ID() == 0) if (getC_Charge_ID() == 0)
{ {
log.saveError("InternalUseNeedsCharge", ""); log.saveError("InternalUseNeedsCharge", "");
return false; return false;
} }
} }
else if (INVENTORYTYPE_ChargeAccount.equals(getInventoryType())) else if (INVENTORYTYPE_ChargeAccount.equals(getInventoryType()))
{ {
if (getC_Charge_ID() == 0) if (getC_Charge_ID() == 0)
{ {
log.saveError("FillMandatory", Msg.getElement(getCtx(), "C_Charge_ID")); log.saveError("FillMandatory", Msg.getElement(getCtx(), "C_Charge_ID"));
return false; return false;
} }
} }
else if (getC_Charge_ID() != 0) else if (getC_Charge_ID() != 0)
setC_Charge_ID(0); setC_Charge_ID(0);
// Set AD_Org to parent if not charge // Set AD_Org to parent if not charge
if (getC_Charge_ID() == 0) if (getC_Charge_ID() == 0)
setAD_Org_ID(getParent().getAD_Org_ID()); setAD_Org_ID(getParent().getAD_Org_ID());
return true; return true;
} // beforeSave } // beforeSave
/** /**
* After Save * After Save
* @param newRecord new * @param newRecord new
* @param success success * @param success success
* @return true * @return true
*/ */
protected boolean afterSave (boolean newRecord, boolean success) protected boolean afterSave (boolean newRecord, boolean success)
{ {
// Create MA // Create MA
if (newRecord && success if (newRecord && success
&& m_isManualEntry && getM_AttributeSetInstance_ID() == 0) && m_isManualEntry && getM_AttributeSetInstance_ID() == 0)
createMA(); createMA();
return true; return true;
} // afterSave } // afterSave
/** /**
* Create Material Allocations for new Instances * Create Material Allocations for new Instances
*/ */
private void createMA() private void createMA()
{ {
MStorage[] storages = MStorage.getAll(getCtx(), getM_Product_ID(), MStorage[] storages = MStorage.getAll(getCtx(), getM_Product_ID(),
getM_Locator_ID(), get_TrxName()); getM_Locator_ID(), get_TrxName());
boolean allZeroASI = true; boolean allZeroASI = true;
for (int i = 0; i < storages.length; i++) for (int i = 0; i < storages.length; i++)
{ {
if (storages[i].getM_AttributeSetInstance_ID() != 0) if (storages[i].getM_AttributeSetInstance_ID() != 0)
{ {
allZeroASI = false; allZeroASI = false;
break; break;
} }
} }
if (allZeroASI) if (allZeroASI)
return; return;
MInventoryLineMA ma = null; MInventoryLineMA ma = null;
BigDecimal sum = Env.ZERO; BigDecimal sum = Env.ZERO;
for (int i = 0; i < storages.length; i++) for (int i = 0; i < storages.length; i++)
{ {
MStorage storage = storages[i]; MStorage storage = storages[i];
if (storage.getQtyOnHand().signum() == 0) if (storage.getQtyOnHand().signum() == 0)
continue; continue;
if (ma != null if (ma != null
&& ma.getM_AttributeSetInstance_ID() == storage.getM_AttributeSetInstance_ID()) && ma.getM_AttributeSetInstance_ID() == storage.getM_AttributeSetInstance_ID())
ma.setMovementQty(ma.getMovementQty().add(storage.getQtyOnHand())); ma.setMovementQty(ma.getMovementQty().add(storage.getQtyOnHand()));
else else
ma = new MInventoryLineMA (this, ma = new MInventoryLineMA (this,
storage.getM_AttributeSetInstance_ID(), storage.getQtyOnHand()); storage.getM_AttributeSetInstance_ID(), storage.getQtyOnHand());
if (!ma.save()) if (!ma.save())
; ;
sum = sum.add(storage.getQtyOnHand()); sum = sum.add(storage.getQtyOnHand());
} }
if (sum.compareTo(getQtyBook()) != 0) if (sum.compareTo(getQtyBook()) != 0)
{ {
log.warning("QtyBook=" + getQtyBook() + " corrected to Sum of MA=" + sum); log.warning("QtyBook=" + getQtyBook() + " corrected to Sum of MA=" + sum);
setQtyBook(sum); setQtyBook(sum);
} }
} // createMA } // createMA
} // MInventoryLine } // MInventoryLine

View File

@ -0,0 +1,56 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms version 2 of the GNU General Public License as published
* by the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Ldap Access Log
*
* @author Jorg Janke
* @version $Id$
*/
public class MLdapAccess extends X_AD_LdapAccess
{
/**
* Standard Constructor
* @param ctx context
* @param AD_LdapAccess_ID id
* @param trxName trx
*/
public MLdapAccess(Properties ctx, int AD_LdapAccess_ID, String trxName)
{
super (ctx, AD_LdapAccess_ID, trxName);
} // MLdapAccess
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MLdapAccess(Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLdapAccess
} // MLdapAccess

View File

@ -0,0 +1,545 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms version 2 of the GNU General Public License as published
* by the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* LDAP Server Model
*
* @author Jorg Janke
* @version $Id$
*/
public class MLdapProcessor extends X_AD_LdapProcessor implements AdempiereProcessor
{
/**
* Get Active LDAP Server
* @return array of Servers
*/
public static MLdapProcessor[] getActive(Properties ctx)
{
ArrayList<MLdapProcessor> list = new ArrayList<MLdapProcessor>();
String sql = "SELECT * FROM AD_LdapProcessor WHERE IsActive='Y'";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MLdapProcessor (ctx, rs, null));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.log (Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MLdapProcessor[] retValue = new MLdapProcessor[list.size()];
list.toArray(retValue);
return retValue;
} // getActive
/** Logger */
private static CLogger log = CLogger.getCLogger (MLdapProcessor.class);
/**************************************************************************
* Ldap Processor
* @param ctx context
* @param AD_LdapProcessor_ID id
* @param trxName transaction
*/
public MLdapProcessor(Properties ctx, int AD_LdapProcessor_ID, String trxName)
{
super (ctx, AD_LdapProcessor_ID, trxName);
} // MLdapProcessor
/**
* Ldap Processor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MLdapProcessor(Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLdapProcessor
/** Array of Clients */
private MClient[] m_clients = null;
/** Array of Interest Areas */
private MInterestArea[] m_interests = null;
private int m_auth = 0;
private int m_ok = 0;
private int m_error = 0;
/**
* Get Server ID
* @return id
*/
public String getServerID ()
{
return "Ldap" + get_ID();
} // getServerID
/**
* Get Info
* @return info
*/
public String getInfo()
{
return "Auth=" + m_auth
+ ", OK=" + m_ok + ", Error=" + m_error;
} // getInfo
/**
* Get Date Next Run
* @param requery requery
* @return date next run
*/
public Timestamp getDateNextRun (boolean requery)
{
if (requery)
load(get_TrxName());
return getDateNextRun();
} // getDateNextRun
/**
* Get Logs
* @return logs
*/
public AdempiereProcessorLog[] getLogs ()
{
ArrayList<MLdapProcessorLog> list = new ArrayList<MLdapProcessorLog>();
String sql = "SELECT * "
+ "FROM AD_LdapProcessorLog "
+ "WHERE AD_LdapProcessor_ID=? "
+ "ORDER BY Created DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getAD_LdapProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MLdapProcessorLog (getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MLdapProcessorLog[] retValue = new MLdapProcessorLog[list.size ()];
list.toArray (retValue);
return retValue;
} // getLogs
/**
* Delete old Request Log
* @return number of records
*/
public int deleteLog()
{
if (getKeepLogDays() < 1)
return 0;
String sql = "DELETE AD_LdapProcessorLog "
+ "WHERE AD_LdapProcessor_ID=" + getAD_LdapProcessor_ID()
+ " AND (Created+" + getKeepLogDays() + ") < SysDate";
int no = DB.executeUpdate(sql, get_TrxName());
return no;
} // deleteLog
/**
* Get Frequency (n/a)
* @return 1
*/
public int getFrequency()
{
return 1;
} // getFrequency
/**
* Get Frequency Type (n/a)
* @return minute
*/
public String getFrequencyType()
{
return X_R_RequestProcessor.FREQUENCYTYPE_Minute;
} // getFrequencyType
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer ("MLdapProcessor[");
sb.append (get_ID()).append ("-").append (getName())
.append (",Port=").append (getLdapPort())
.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
* Authenticate and Authorize
* @param ldapUser MLdapUser object
* @param usr user name
* @param o organization = Client Name
* @param ou optional organization unit = Interest Group
* @return ldapUser MLdapUser with updated information
*/
public MLdapUser authenticate(MLdapUser ldapUser, String usr, String o, String ou)
{
// Ensure something to return
if (ldapUser == null)
ldapUser = new MLdapUser();
String error = null;
String info = null;
// User
if (usr == null || usr.trim().length () == 0)
{
error = "@NotFound@ User";
ldapUser.setErrorString(error);
m_error++;
log.warning (error);
return ldapUser;
}
usr = usr.trim();
// Client
if (o == null || o.length () == 0)
{
error = "@NotFound@ O";
ldapUser.setErrorString(error);
m_error++;
log.warning (error);
return ldapUser;
}
int AD_Client_ID = findClient(o);
if (AD_Client_ID == 0)
{
error = "@NotFound@ O=" + o;
ldapUser.setErrorString(error);
m_error++;
log.config (error);
return ldapUser;
}
// Optional Interest Area
int R_InterestArea_ID = 0;
if (ou != null && ou.length () > 0)
{
R_InterestArea_ID = findInterestArea (AD_Client_ID, ou);
if (R_InterestArea_ID == 0)
{
error = "@NotFound@ OU=" + ou;
ldapUser.setErrorString(error);
m_error++;
log.config (error);
return ldapUser;
}
}
m_auth++;
// Query 1 - Validate User
int AD_User_ID = 0;
String Value = null;
String LdapUser = null;
String EMail = null;
String Name = null;
String Password = null;
boolean IsActive = false;
String EMailVerify = null; // is timestamp
boolean isUnique = false;
//
String sql = "SELECT AD_User_ID, Value, LdapUser, EMail," // 1..4
+ " Name, Password, IsActive, EMailVerify "
+ "FROM AD_User "
+ "WHERE AD_Client_ID=? AND (EMail=? OR Value=? OR LdapUser=?)";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, AD_Client_ID);
pstmt.setString (2, usr);
pstmt.setString (3, usr);
pstmt.setString (4, usr);
ResultSet rs = pstmt.executeQuery ();
if (rs.next())
{
AD_User_ID = rs.getInt (1);
Value = rs.getString (2);
LdapUser = rs.getString (3);
EMail = rs.getString (4);
//
Name = rs.getString (5);
Password = rs.getString (6);
IsActive = "Y".equals (rs.getString (7));
EMailVerify = rs.getString (8);
isUnique = rs.next();
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.log (Level.SEVERE, sql, e);
error = "System Error";
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
if (error != null)
{
m_error++;
ldapUser.setErrorString(error);
return ldapUser;
}
//
if (AD_User_ID == 0)
{
error = "@NotFound@ User=" + usr;
info = "User not found - " + usr;
}
else if (!IsActive)
{
error = "@NotFound@ User=" + usr;
info = "User not active - " + usr;
}
else if (EMailVerify == null)
{
error = "@UserNotVerified@ User=" + usr;
info = "User EMail not verified - " + usr;
}
else if (usr.equalsIgnoreCase(LdapUser))
info = "User verified - Ldap=" + usr
+ (isUnique ? "" : " - Not Unique");
else if (usr.equalsIgnoreCase(Value))
info = "User verified - Value=" + usr
+ (isUnique ? "" : " - Not Unique");
else if (usr.equalsIgnoreCase(EMail))
info = "User verified - EMail=" + usr
+ (isUnique ? "" : " - Not Unique");
else
info = "User verified ?? " + usr
+ " - Name=" + Name
+ ", Ldap=" + LdapUser + ", Value=" + Value
+ (isUnique ? "" : " - Not Unique");
// Error
if (error != null) // should use Language of the User
{
logAccess (AD_Client_ID, AD_User_ID, R_InterestArea_ID, info, error);
ldapUser.setErrorString(Msg.translate (getCtx(), error));
return ldapUser;
}
// Done
if (R_InterestArea_ID == 0)
{
logAccess (AD_Client_ID, AD_User_ID, R_InterestArea_ID, info, null);
ldapUser.setOrg(o);
ldapUser.setOrgUnit(ou);
ldapUser.setUserId(usr);
ldapUser.setPassword(Password);
return ldapUser;
}
// Query 2 - Validate Subscription
String OptOutDate = null;
boolean found = false;
sql = "SELECT IsActive, OptOutDate "
+ "FROM R_ContactInterest "
+ "WHERE R_InterestArea_ID=? AND AD_User_ID=?";
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, R_InterestArea_ID);
pstmt.setInt (2, AD_User_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next())
{
found = true;
IsActive = "Y".equals (rs.getString (1));
OptOutDate = rs.getString (2);
isUnique = rs.next();
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.log (Level.SEVERE, sql, e);
error = "System Error (2)";
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
// System Error
if (error != null)
{
m_error++;
ldapUser.setErrorString(error);
return ldapUser;
}
if (!found)
{
error = "@UserNotSubscribed@ User=" + usr;
info = "No User Interest - " + usr
+ " - R_InterestArea_ID=" + R_InterestArea_ID;
}
else if (OptOutDate != null)
{
error = "@UserNotSubscribed@ User=" + usr + " @OptOutDate@=" + OptOutDate;
info = "Opted out - " + usr + " - OptOutDate=" + OptOutDate;
}
else if (!IsActive)
{
error = "@UserNotSubscribed@ User=" + usr;
info = "User Interest Not Active - " + usr;
}
else
info = "User subscribed - " + usr;
if (error != null) // should use Language of the User
{
logAccess (AD_Client_ID, AD_User_ID, R_InterestArea_ID, info, error);
ldapUser.setErrorString(Msg.translate (getCtx(), error));
return ldapUser;
}
// Done
logAccess (AD_Client_ID, AD_User_ID, R_InterestArea_ID, info, null);
ldapUser.setOrg(o);
ldapUser.setOrgUnit(ou);
ldapUser.setUserId(usr);
ldapUser.setPassword(Password);
return ldapUser;
} // authenticate
/**
* Find Client
* @param client client name
* @return AD_Client_ID
*/
private int findClient (String client)
{
if (m_clients == null)
m_clients = MClient.getAll(getCtx());
for (int i = 0; i < m_clients.length; i++)
{
if ((client.equalsIgnoreCase (m_clients[i].getValue())))
return m_clients[i].getAD_Client_ID ();
}
return 0;
} // findClient
/**
* Find Interest Area
* @param interset Name client name
* @return AD_Client_ID
*/
private int findInterestArea (int AD_Client_ID, String interestArea)
{
if (m_interests == null)
m_interests = MInterestArea.getAll(getCtx());
for (int i = 0; i < m_interests.length; i++)
{
if (AD_Client_ID == m_interests[i].getAD_Client_ID()
&& interestArea.equalsIgnoreCase (m_interests[i].getValue ()))
return m_interests[i].getR_InterestArea_ID();
}
return 0;
} // findInterestArea
/**
* Log Access
* @param AD_Client_ID client
* @param AD_User_ID user
* @param R_InterestArea_ID interest area
* @param info info
* @param error error
*/
private void logAccess (int AD_Client_ID,
int AD_User_ID, int R_InterestArea_ID,
String info, String error)
{
if (error != null)
{
log.log (Level.CONFIG, info);
m_error++;
}
else
{
log.log (Level.INFO, info);
m_ok++;
}
//
MLdapAccess access = new MLdapAccess (getCtx(), 0, null);
access.setAD_Client_ID (AD_Client_ID);
access.setAD_User_ID (AD_User_ID);
access.setR_InterestArea_ID (R_InterestArea_ID);
access.setIsError (error != null);
access.setSummary (info);
access.save ();
} // logAccess
} // MLdapProcessor

View File

@ -0,0 +1,72 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms version 2 of the GNU General Public License as published
* by the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* LDAP Server Log
* @author Jorg Janke
* @version $Id$
*/
public class MLdapProcessorLog extends X_AD_LdapProcessorLog implements AdempiereProcessorLog
{
/**
* Standard Constructor
* @param ctx context
* @param AD_LdapProcessorLog_ID id
* @param trxName trx
*/
public MLdapProcessorLog(Properties ctx, int AD_LdapProcessorLog_ID,
String trxName)
{
super (ctx, AD_LdapProcessorLog_ID, trxName);
if (AD_LdapProcessorLog_ID == 0)
{
// setAD_LdapProcessorLog_ID (0);
// setAD_LdapProcessor_ID (0);
setIsError (false);
}
} // MLdapProcessorLog
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MLdapProcessorLog(Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLdapProcessorLog
/**
* Parent Constructor
* @param parent parent
* @param summary summary
*/
public MLdapProcessorLog(MLdapProcessor parent, String summary)
{
this (parent.getCtx (), 0, null);
setClientOrg (parent);
setAD_LdapProcessor_ID (parent.getAD_LdapProcessor_ID());
setSummary (summary);
} // MLdapProcessorLog
} // MLdapProcessorLog

View File

@ -0,0 +1,140 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or modify it
* under the terms version 2 of the GNU General Public License as published
* by the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org
*****************************************************************************/
package org.compiere.model;
/*
* MLdapUser, data object stores the user information such as userid,
* password, organization and so on.
*/
public class MLdapUser
{
/** organization */
private String org = null;
/** organization unit */
private String orgUnit = null;
/** user password */
private String passwd = null;
/** user id */
private String userId = null;
/** error string */
private String errStr = null;
public MLdapUser()
{
}
/*
* Reset attributes
*/
public void reset()
{
org = null;
orgUnit = null;
passwd = null;
userId = null;
errStr = null;
} // reset()
/**
* Set the organization
* @param org organization
*/
public void setOrg(String org)
{
this.org = org;
} // setOrg()
/**
* Set the organization unit
* @param orgUnit organization unit
*/
public void setOrgUnit(String orgUnit)
{
this.orgUnit = orgUnit;
} // setOrg()
/**
* Set the user password
* @param passwd User password string
*/
public void setPassword(String passwd)
{
this.passwd = passwd;
} // setPassword()
/**
* Set the user id
* @param passwd User id string
*/
public void setUserId(String userId)
{
this.userId = userId;
} // setUserId()
/**
* Set the error String
* @param errStr Error String
*/
public void setErrorString(String errStr)
{
this.errStr = errStr;
} // setErrorStr()
/**
* Get the organization
* @return org organization
*/
public String getOrg()
{
return org;
} // getOrg()
/**
* Get the organization unit
* @return orgUnit organization unit
*/
public String getOrgUnit()
{
return orgUnit;
} // getOrgUnit()
/**
* Get the user password
* @return passwd User password string
*/
public String getPassword()
{
return passwd;
} // getPassword()
/**
* Get the user id
* @return User id string
*/
public String getUserId()
{
return userId;
} // getUserId()
/**
* Get the error string
* @return errStr Error String
*/
public String getErrorMsg()
{
return errStr;
} // getErrorString()
} // MLdapUser

View File

@ -3,167 +3,181 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Inventory Move Line Model * Inventory Move Line Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MMovementLine.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ * @version $Id: MMovementLine.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/ */
public class MMovementLine extends X_M_MovementLine public class MMovementLine extends X_M_MovementLine
{ {
/** /**
* Standard Cosntructor * Standard Cosntructor
* @param ctx context * @param ctx context
* @param M_MovementLine_ID id * @param M_MovementLine_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MMovementLine (Properties ctx, int M_MovementLine_ID, String trxName) public MMovementLine (Properties ctx, int M_MovementLine_ID, String trxName)
{ {
super (ctx, M_MovementLine_ID, trxName); super (ctx, M_MovementLine_ID, trxName);
if (M_MovementLine_ID == 0) if (M_MovementLine_ID == 0)
{ {
// setM_LocatorTo_ID (0); // @M_LocatorTo_ID@ // setM_LocatorTo_ID (0); // @M_LocatorTo_ID@
// setM_Locator_ID (0); // @M_Locator_ID@ // setM_Locator_ID (0); // @M_Locator_ID@
// setM_MovementLine_ID (0); // setM_MovementLine_ID (0);
// setLine (0); // setLine (0);
// setM_Product_ID (0); // setM_Product_ID (0);
setM_AttributeSetInstance_ID(0); // ID setM_AttributeSetInstance_ID(0); // ID
setMovementQty (Env.ZERO); // 1 setMovementQty (Env.ZERO); // 1
setTargetQty (Env.ZERO); // 0 setTargetQty (Env.ZERO); // 0
setScrappedQty(Env.ZERO); setScrappedQty(Env.ZERO);
setConfirmedQty(Env.ZERO); setConfirmedQty(Env.ZERO);
setProcessed (false); setProcessed (false);
} }
} // MMovementLine } // MMovementLine
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MMovementLine (Properties ctx, ResultSet rs, String trxName) public MMovementLine (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MMovementLine } // MMovementLine
/** /**
* Parent constructor * Parent constructor
* @param parent parent * @param parent parent
*/ */
public MMovementLine (MMovement parent) public MMovementLine (MMovement parent)
{ {
this (parent.getCtx(), 0, parent.get_TrxName()); this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent); setClientOrg(parent);
setM_Movement_ID(parent.getM_Movement_ID()); setM_Movement_ID(parent.getM_Movement_ID());
} // MMovementLine } // MMovementLine
/** /**
* Get AttributeSetInstance To * Get AttributeSetInstance To
* @return ASI * @return ASI
*/ */
public int getM_AttributeSetInstanceTo_ID () public int getM_AttributeSetInstanceTo_ID ()
{ {
int M_AttributeSetInstanceTo_ID = super.getM_AttributeSetInstanceTo_ID(); int M_AttributeSetInstanceTo_ID = super.getM_AttributeSetInstanceTo_ID();
if (M_AttributeSetInstanceTo_ID == 0) if (M_AttributeSetInstanceTo_ID == 0)
M_AttributeSetInstanceTo_ID = super.getM_AttributeSetInstance_ID(); M_AttributeSetInstanceTo_ID = super.getM_AttributeSetInstance_ID();
return M_AttributeSetInstanceTo_ID; return M_AttributeSetInstanceTo_ID;
} // getM_AttributeSetInstanceTo_ID } // getM_AttributeSetInstanceTo_ID
/** /**
* Add to Description * Add to Description
* @param description text * @param description text
*/ */
public void addDescription (String description) public void addDescription (String description)
{ {
String desc = getDescription(); String desc = getDescription();
if (desc == null) if (desc == null)
setDescription(description); setDescription(description);
else else
setDescription(desc + " | " + description); setDescription(desc + " | " + description);
} // addDescription } // addDescription
/** /**
* Get Product * Get Product
* @return product or null if not defined * @return product or null if not defined
*/ */
public MProduct getProduct() public MProduct getProduct()
{ {
if (getM_Product_ID() != 0) if (getM_Product_ID() != 0)
return MProduct.get(getCtx(), getM_Product_ID()); return MProduct.get(getCtx(), getM_Product_ID());
return null; return null;
} // getProduct } // getProduct
/** /**
* Set Movement Qty - enforce UOM * Set Movement Qty - enforce UOM
* @param MovementQty qty * @param MovementQty qty
*/ */
public void setMovementQty (BigDecimal MovementQty) public void setMovementQty (BigDecimal MovementQty)
{ {
if (MovementQty != null) if (MovementQty != null)
{ {
MProduct product = getProduct(); MProduct product = getProduct();
if (product != null) if (product != null)
{ {
int precision = product.getUOMPrecision(); int precision = product.getUOMPrecision();
MovementQty = MovementQty.setScale(precision, BigDecimal.ROUND_HALF_UP); MovementQty = MovementQty.setScale(precision, BigDecimal.ROUND_HALF_UP);
} }
} }
super.setMovementQty(MovementQty); super.setMovementQty(MovementQty);
} // setMovementQty } // setMovementQty
/** Parent */
private MMovement m_parent = null;
/**
* get Parent
* @return Parent Movement
*/
public MMovement getParent()
{
if (m_parent == null)
m_parent = new MMovement (getCtx(), getM_Movement_ID(), get_TrxName());
return m_parent;
} // getParent
/** /**
* Before Save * Before Save
* @param newRecord new * @param newRecord new
* @return true * @return true
*/ */
protected boolean beforeSave (boolean newRecord) protected boolean beforeSave (boolean newRecord)
{ {
// Set Line No // Set Line No
if (getLine() == 0) if (getLine() == 0)
{ {
String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_MovementLine WHERE M_Movement_ID=?"; String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_M_MovementLine WHERE M_Movement_ID=?";
int ii = DB.getSQLValue (get_TrxName(), sql, getM_Movement_ID()); int ii = DB.getSQLValue (get_TrxName(), sql, getM_Movement_ID());
setLine (ii); setLine (ii);
} }
if (getM_Locator_ID() == getM_LocatorTo_ID()) if (getM_Locator_ID() == getM_LocatorTo_ID())
{ {
log.saveError("Error", Msg.parseTranslation(getCtx(), "@M_Locator_ID@ == @M_LocatorTo_ID@")); log.saveError("Error", Msg.parseTranslation(getCtx(), "@M_Locator_ID@ == @M_LocatorTo_ID@"));
return false; return false;
} }
if (getMovementQty().signum() == 0) if (getMovementQty().signum() == 0)
{ {
log.saveError("FillMandatory", Msg.getElement(getCtx(), "MovementQty")); log.saveError("FillMandatory", Msg.getElement(getCtx(), "MovementQty"));
return false; return false;
} }
// Qty Precision // Qty Precision
if (newRecord || is_ValueChanged("QtyEntered")) if (newRecord || is_ValueChanged("QtyEntered"))
setMovementQty(getMovementQty()); setMovementQty(getMovementQty());
return true; return true;
} // beforeSave } // beforeSave
} // MMovementLine } // MMovementLine

View File

@ -3,135 +3,134 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
/** /**
* News ItemModel * News ItemModel
* *
* @author Yves Sandfort * @author Yves Sandfort
* @version $Id$ * @version $Id$
*/ */
public class MNewsItem extends X_CM_NewsItem public class MNewsItem extends X_CM_NewsItem
{ {
/*** /***
* Standard Constructor * Standard Constructor
* *
* @param ctx context * @param ctx context
* @param CM_NewsItem_ID id * @param CM_NewsItem_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MNewsItem (Properties ctx, int CM_NewsItem_ID, String trxName) public MNewsItem (Properties ctx, int CM_NewsItem_ID, String trxName)
{ {
super (ctx, CM_NewsItem_ID, trxName); super (ctx, CM_NewsItem_ID, trxName);
} // MNewsItem } // MNewsItem
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MNewsItem (Properties ctx, ResultSet rs, String trxName) public MNewsItem (Properties ctx, ResultSet rs, String trxName)
{ {
super (ctx, rs, trxName); super (ctx, rs, trxName);
} // MNewsItem } // MNewsItem
/** /**
* getNewsChannel * getNewsChannel
* @return NewsChannel * @return NewsChannel
*/ */
public MNewsChannel getNewsChannel() public MNewsChannel getNewsChannel()
{ {
int[] thisNewsChannel = MNewsChannel.getAllIDs("CM_NewsChannel","CM_NewsChannel_ID=" + this.getCM_NewsChannel_ID(), get_TrxName()); int[] thisNewsChannel = MNewsChannel.getAllIDs("CM_NewsChannel","CM_NewsChannel_ID=" + this.getCM_NewsChannel_ID(), get_TrxName());
if (thisNewsChannel!=null) if (thisNewsChannel!=null)
{ {
if (thisNewsChannel.length==1) if (thisNewsChannel.length==1)
return new MNewsChannel(getCtx(), thisNewsChannel[0], get_TrxName()); return new MNewsChannel(getCtx(), thisNewsChannel[0], get_TrxName());
} }
return null; return null;
} // getNewsChannel } // getNewsChannel
/** /**
* Get rss2 Item Code * Get rss2 Item Code
* @param xmlCode xml * @param xmlCode xml
* @param thisChannel channel * @param thisChannel channel
* @return rss item code * @return rss item code
*/ */
public StringBuffer get_rss2ItemCode(StringBuffer xmlCode, MNewsChannel thisChannel) public StringBuffer get_rss2ItemCode(StringBuffer xmlCode, MNewsChannel thisChannel)
{ {
if (this != null) // never null ?? if (this != null) // never null ??
{ {
xmlCode.append ("<item>"); xmlCode.append ("<item>");
xmlCode.append ("<CM_NewsItem_ID>"+ this.get_ID() + "</CM_NewsItem_ID>"); xmlCode.append ("<CM_NewsItem_ID>"+ this.get_ID() + "</CM_NewsItem_ID>");
xmlCode.append (" <title><![CDATA[" xmlCode.append (" <title><![CDATA["
+ this.getTitle () + "]]></title>"); + this.getTitle () + "]]></title>");
xmlCode.append (" <description><![CDATA[" xmlCode.append (" <description><![CDATA["
+ this.getDescription () + this.getDescription ()
+ "]]></description>"); + "]]></description>");
xmlCode.append (" <content><![CDATA[" xmlCode.append (" <content><![CDATA["
+ this.getContentHTML () + this.getContentHTML ()
+ "]]></content>"); + "]]></content>");
xmlCode.append (" <link>" xmlCode.append (" <link>"
+ thisChannel.getLink () + thisChannel.getLink ()
+ "?CM_NewsItem_ID=" + this.get_ID() + "</link>"); + "?CM_NewsItem_ID=" + this.get_ID() + "</link>");
xmlCode.append (" <author><![CDATA[" xmlCode.append (" <author><![CDATA["
+ this.getAuthor () + "]]></author>"); + this.getAuthor () + "]]></author>");
xmlCode.append (" <pubDate>" xmlCode.append (" <pubDate>"
+ this.getPubDate () + "</pubDate>"); + this.getPubDate () + "</pubDate>");
xmlCode.append ("</item>"); xmlCode.append ("</item>");
} }
return xmlCode; return xmlCode;
} }
/** /**
* After Save. * After Save.
* Insert * Insert
* - create / update index * - create / update index
* @param newRecord insert * @param newRecord insert
* @param success save success * @param success save success
* @return true if saved * @return true if saved
*/ */
protected boolean afterSave (boolean newRecord, boolean success) protected boolean afterSave (boolean newRecord, boolean success)
{ {
if (!success) if (!success)
return success; return success;
if (!newRecord) if (!newRecord)
{ {
MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID()); MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID());
} }
reIndex(newRecord); reIndex(newRecord);
return success; return success;
} // afterSave } // afterSave
/** /**
* reIndex * reIndex
* @param newRecord * @param newRecord
* @throws SQLException
*/ */
public void reIndex(boolean newRecord) public void reIndex(boolean newRecord)
{ {
int CMWebProjectID = 0; int CMWebProjectID = 0;
if (getNewsChannel()!=null) if (getNewsChannel()!=null)
CMWebProjectID = getNewsChannel().getCM_WebProject_ID(); CMWebProjectID = getNewsChannel().getCM_WebProject_ID();
String [] toBeIndexed = new String[4]; String [] toBeIndexed = new String[4];
toBeIndexed[0] = this.getAuthor(); toBeIndexed[0] = this.getAuthor();
toBeIndexed[1] = this.getDescription(); toBeIndexed[1] = this.getDescription();
toBeIndexed[2] = this.getTitle(); toBeIndexed[2] = this.getTitle();
toBeIndexed[3] = this.getContentHTML(); toBeIndexed[3] = this.getContentHTML();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated()); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated());
} // reIndex } // reIndex
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,176 +3,175 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Payment Selection Line Model * Payment Selection Line Model
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MPaySelectionLine.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ * @version $Id: MPaySelectionLine.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/ */
public class MPaySelectionLine extends X_C_PaySelectionLine public class MPaySelectionLine extends X_C_PaySelectionLine
{ {
/** /**
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param C_PaySelectionLine_ID id * @param C_PaySelectionLine_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MPaySelectionLine (Properties ctx, int C_PaySelectionLine_ID, String trxName) public MPaySelectionLine (Properties ctx, int C_PaySelectionLine_ID, String trxName)
{ {
super(ctx, C_PaySelectionLine_ID, trxName); super(ctx, C_PaySelectionLine_ID, trxName);
if (C_PaySelectionLine_ID == 0) if (C_PaySelectionLine_ID == 0)
{ {
// setC_PaySelection_ID (0); // setC_PaySelection_ID (0);
// setPaymentRule (null); // S // setPaymentRule (null); // S
// setLine (0); // @SQL=SELECT NVL(MAX(Line),0)+10 AS DefaultValue FROM C_PaySelectionLine WHERE C_PaySelection_ID=@C_PaySelection_ID@ // setLine (0); // @SQL=SELECT NVL(MAX(Line),0)+10 AS DefaultValue FROM C_PaySelectionLine WHERE C_PaySelection_ID=@C_PaySelection_ID@
// setC_Invoice_ID (0); // setC_Invoice_ID (0);
setIsSOTrx (false); setIsSOTrx (false);
setOpenAmt(Env.ZERO); setOpenAmt(Env.ZERO);
setPayAmt (Env.ZERO); setPayAmt (Env.ZERO);
setDiscountAmt(Env.ZERO); setDiscountAmt(Env.ZERO);
setDifferenceAmt (Env.ZERO); setDifferenceAmt (Env.ZERO);
setIsManual (false); setIsManual (false);
} }
} // MPaySelectionLine } // MPaySelectionLine
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MPaySelectionLine(Properties ctx, ResultSet rs, String trxName) public MPaySelectionLine(Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MPaySelectionLine } // MPaySelectionLine
/** /**
* Parent Constructor * Parent Constructor
* @param ps parent * @param ps parent
* @param Line line * @param Line line
* @param PaymentRule payment rule * @param PaymentRule payment rule
*/ */
public MPaySelectionLine (MPaySelection ps, int Line, String PaymentRule) public MPaySelectionLine (MPaySelection ps, int Line, String PaymentRule)
{ {
this (ps.getCtx(), 0, ps.get_TrxName()); this (ps.getCtx(), 0, ps.get_TrxName());
setClientOrg(ps); setClientOrg(ps);
setC_PaySelection_ID(ps.getC_PaySelection_ID()); setC_PaySelection_ID(ps.getC_PaySelection_ID());
setLine(Line); setLine(Line);
setPaymentRule(PaymentRule); setPaymentRule(PaymentRule);
} // MPaySelectionLine } // MPaySelectionLine
/** Invoice */ /** Invoice */
private MInvoice m_invoice = null; private MInvoice m_invoice = null;
/** /**
* Set Invoice Info * Set Invoice Info
* @param C_Invoice_ID invoice * @param C_Invoice_ID invoice
* @param isSOTrx sales trx * @param isSOTrx sales trx
* @param PayAmt payment * @param PayAmt payment
* @param OpenAmt open * @param OpenAmt open
* @param DiscountAmt discount * @param DiscountAmt discount
*/ */
public void setInvoice (int C_Invoice_ID, boolean isSOTrx, BigDecimal OpenAmt, public void setInvoice (int C_Invoice_ID, boolean isSOTrx, BigDecimal OpenAmt,
BigDecimal PayAmt, BigDecimal DiscountAmt) BigDecimal PayAmt, BigDecimal DiscountAmt)
{ {
setC_Invoice_ID (C_Invoice_ID); setC_Invoice_ID (C_Invoice_ID);
setIsSOTrx(isSOTrx); setIsSOTrx(isSOTrx);
setOpenAmt(OpenAmt); setOpenAmt(OpenAmt);
setPayAmt (PayAmt); setPayAmt (PayAmt);
setDiscountAmt(DiscountAmt); setDiscountAmt(DiscountAmt);
setDifferenceAmt(OpenAmt.subtract(PayAmt).subtract(DiscountAmt)); setDifferenceAmt(OpenAmt.subtract(PayAmt).subtract(DiscountAmt));
} // setInvoive } // setInvoive
/** /**
* Get Invoice * Get Invoice
* @return invoice * @return invoice
*/ */
public MInvoice getInvoice() public MInvoice getInvoice()
{ {
if (m_invoice == null) if (m_invoice == null)
m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName()); m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName());
return m_invoice; return m_invoice;
} // getInvoice } // getInvoice
/** /**
* Before Save * Before Save
* @param newRecord new * @param newRecord new
* @return true * @return true
*/ */
protected boolean beforeSave (boolean newRecord) protected boolean beforeSave (boolean newRecord)
{ {
setDifferenceAmt(getOpenAmt().subtract(getPayAmt()).subtract(getDiscountAmt())); setDifferenceAmt(getOpenAmt().subtract(getPayAmt()).subtract(getDiscountAmt()));
return true; return true;
} // beforeSave } // beforeSave
/** /**
* After Save * After Save
* @param newRecord new * @param newRecord new
* @param success success * @param success success
* @return success * @return success
*/ */
protected boolean afterSave (boolean newRecord, boolean success) protected boolean afterSave (boolean newRecord, boolean success)
{ {
setHeader(); setHeader();
return success; return success;
} // afterSave } // afterSave
/** /**
* After Delete * After Delete
* @param success success * @param success success
* @return sucess * @return sucess
*/ */
protected boolean afterDelete (boolean success) protected boolean afterDelete (boolean success)
{ {
setHeader(); setHeader();
return success; return success;
} // afterDelete } // afterDelete
/** /**
* Recalculate Header Sum * Recalculate Header Sum
*/ */
private void setHeader() private void setHeader()
{ {
// Update Header // Update Header
String sql = "UPDATE C_PaySelection ps " String sql = "UPDATE C_PaySelection ps "
+ "SET TotalAmt = (SELECT COALESCE(SUM(psl.PayAmt),0) " + "SET TotalAmt = (SELECT COALESCE(SUM(psl.PayAmt),0) "
+ "FROM C_PaySelectionLine psl " + "FROM C_PaySelectionLine psl "
+ "WHERE ps.C_PaySelection_ID=psl.C_PaySelection_ID AND psl.IsActive='Y') " + "WHERE ps.C_PaySelection_ID=psl.C_PaySelection_ID AND psl.IsActive='Y') "
+ "WHERE C_PaySelection_ID=" + getC_PaySelection_ID(); + "WHERE C_PaySelection_ID=" + getC_PaySelection_ID();
DB.executeUpdate(sql, get_TrxName()); DB.executeUpdate(sql, get_TrxName());
} // setHeader } // setHeader
/** /**
* String Representation * String Representation
* @return info * @return info
*/ */
public String toString() public String toString()
{ {
StringBuffer sb = new StringBuffer("MPaySelectionLine["); StringBuffer sb = new StringBuffer("MPaySelectionLine[");
sb.append(get_ID()).append(",C_Invoice_ID=").append(getC_Invoice_ID()) sb.append(get_ID()).append(",C_Invoice_ID=").append(getC_Invoice_ID())
.append(",PayAmt=").append(getPayAmt()) .append(",PayAmt=").append(getPayAmt())
.append(",DifferenceAmt=").append(getDifferenceAmt()) .append(",DifferenceAmt=").append(getDifferenceAmt())
.append("]"); .append("]");
return sb.toString(); return sb.toString();
} // toString } // toString
} // MPaySelectionLine } // MPaySelectionLine

File diff suppressed because it is too large Load Diff

View File

@ -3,436 +3,438 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.util.*; import java.util.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Payment Validion Routines * Payment Validion Routines
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MPaymentValidate.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $ * @version $Id: MPaymentValidate.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/ */
public class MPaymentValidate public class MPaymentValidate
{ {
/** Static Logger */ /** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MPaymentValidate.class); private static CLogger s_log = CLogger.getCLogger (MPaymentValidate.class);
/** /**
* Is this a valid Credit Card Exp Date? * Is this a valid Credit Card Exp Date?
* @param mmyy Exp in form of mmyy * @param mmyy Exp in form of mmyy
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardExp (String mmyy) public static String validateCreditCardExp (String mmyy)
{ {
String exp = checkNumeric(mmyy); String exp = checkNumeric(mmyy);
if (exp.length() != 4) if (exp.length() != 4)
return "CreditCardExpFormat"; return "CreditCardExpFormat";
// //
String mmStr = exp.substring(0,2); String mmStr = exp.substring(0,2);
String yyStr = exp.substring(2,4); String yyStr = exp.substring(2,4);
// //
int mm = 0; int mm = 0;
int yy = 0; int yy = 0;
try try
{ {
mm = Integer.parseInt(mmStr); mm = Integer.parseInt(mmStr);
yy = Integer.parseInt(yyStr); yy = Integer.parseInt(yyStr);
} }
catch (Exception e) catch (Exception e)
{ {
return "CreditCardExpFormat"; return "CreditCardExpFormat";
} }
return validateCreditCardExp(mm,yy); return validateCreditCardExp(mm,yy);
} // validateCreditCardExp } // validateCreditCardExp
/** /**
* Return Month of Exp * Return Month of Exp
* @param mmyy Exp in form of mmyy * @param mmyy Exp in form of mmyy
* @return month * @return month
*/ */
public static int getCreditCardExpMM (String mmyy) public static int getCreditCardExpMM (String mmyy)
{ {
String mmStr = mmyy.substring(0,2); String mmStr = mmyy.substring(0,2);
int mm = 0; int mm = 0;
try try
{ {
mm = Integer.parseInt(mmStr); mm = Integer.parseInt(mmStr);
} }
catch (Exception e) catch (Exception e)
{ {
} }
return mm; return mm;
} // getCreditCardExpMM } // getCreditCardExpMM
/** /**
* Return Year of Exp * Return Year of Exp
* @param mmyy Exp in form of mmyy * @param mmyy Exp in form of mmyy
* @return year * @return year
*/ */
public static int getCreditCardExpYY (String mmyy) public static int getCreditCardExpYY (String mmyy)
{ {
String yyStr = mmyy.substring(2); String yyStr = mmyy.substring(2);
int yy = 0; int yy = 0;
try try
{ {
yy = Integer.parseInt(yyStr); yy = Integer.parseInt(yyStr);
} }
catch (Exception e) catch (Exception e)
{ {
} }
return yy; return yy;
} // getCreditCardExpYY } // getCreditCardExpYY
/** /**
* Is this a valid Credit Card Exp Date? * Is this a valid Credit Card Exp Date?
* @param mm month * @param mm month
* @param yy year * @param yy year
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardExp (int mm, int yy) public static String validateCreditCardExp (int mm, int yy)
{ {
if (mm < 1 || mm > 12) if (mm < 1 || mm > 12)
return "CreditCardExpMonth"; return "CreditCardExpMonth";
// if (yy < 0 || yy > EXP_YEAR) // if (yy < 0 || yy > EXP_YEAR)
// return "CreditCardExpYear"; // return "CreditCardExpYear";
// Today's date // Today's date
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR) - 2000; // two digits int year = cal.get(Calendar.YEAR) - 2000; // two digits
int month = cal.get(Calendar.MONTH) + 1; // zero based int month = cal.get(Calendar.MONTH) + 1; // zero based
// //
if (yy < year) if (yy < year)
return "CreditCardExpired"; return "CreditCardExpired";
else if (yy == year && mm < month) else if (yy == year && mm < month)
return "CreditCardExpired"; return "CreditCardExpired";
return ""; return "";
} // validateCreditCardExp } // validateCreditCardExp
/** /**
* Validate Credit Card Number. * Validate Credit Card Number.
* - Based on LUHN formula * - Based on LUHN formula
* @param creditCardNumber credit card number * @param creditCardNumber credit card number
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardNumber (String creditCardNumber) public static String validateCreditCardNumber (String creditCardNumber)
{ {
if (creditCardNumber == null || creditCardNumber.length() == 0) if (creditCardNumber == null || creditCardNumber.length() == 0)
return "CreditCardNumberError"; return "CreditCardNumberError";
/** /**
* 1: Double the value of alternate digits beginning with * 1: Double the value of alternate digits beginning with
* the first right-hand digit (low order). * the first right-hand digit (low order).
* 2: Add the individual digits comprising the products * 2: Add the individual digits comprising the products
* obtained in step 1 to each of the unaffected digits * obtained in step 1 to each of the unaffected digits
* in the original number. * in the original number.
* 3: Subtract the total obtained in step 2 from the next higher * 3: Subtract the total obtained in step 2 from the next higher
* number ending in 0 [this in the equivalent of calculating * number ending in 0 [this in the equivalent of calculating
* the "tens complement" of the low order digit (unit digit) * the "tens complement" of the low order digit (unit digit)
* of the total]. * of the total].
* If the total obtained in step 2 is a number ending in zero * If the total obtained in step 2 is a number ending in zero
* (30, 40 etc.), the check digit is 0. * (30, 40 etc.), the check digit is 0.
* Example: * Example:
* Account number: 4992 73 9871 6 * Account number: 4992 73 9871 6
* *
* 4 9 9 2 7 3 9 8 7 1 6 * 4 9 9 2 7 3 9 8 7 1 6
* x2 x2 x2 x2 x2 * x2 x2 x2 x2 x2
* ------------------------------- * -------------------------------
* 4 18 9 4 7 6 9 16 7 2 6 * 4 18 9 4 7 6 9 16 7 2 6
* *
* 4 + 1 + 8 + 9 + 4 + 7 + 6 + 9 + 1 + 6 + 7 + 2 + 6 = 70 * 4 + 1 + 8 + 9 + 4 + 7 + 6 + 9 + 1 + 6 + 7 + 2 + 6 = 70
* 70 % 10 = 0 * 70 % 10 = 0
*/ */
// Clean up number // Clean up number
String ccNumber1 = checkNumeric(creditCardNumber); String ccNumber1 = checkNumeric(creditCardNumber);
int ccLength = ccNumber1.length(); int ccLength = ccNumber1.length();
// Reverse string // Reverse string
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
for (int i = ccLength; i != 0; i--) for (int i = ccLength; i != 0; i--)
buf.append(ccNumber1.charAt(i-1)); buf.append(ccNumber1.charAt(i-1));
String ccNumber = buf.toString(); String ccNumber = buf.toString();
int sum = 0; int sum = 0;
for (int i = 0; i < ccLength; i++) for (int i = 0; i < ccLength; i++)
{ {
int digit = Character.getNumericValue(ccNumber.charAt(i)); int digit = Character.getNumericValue(ccNumber.charAt(i));
if (i % 2 == 1) if (i % 2 == 1)
{ {
digit *= 2; digit *= 2;
if (digit > 9) if (digit > 9)
digit -= 9; digit -= 9;
} }
sum += digit; sum += digit;
} }
if (sum % 10 == 0) if (sum % 10 == 0)
return ""; return "";
s_log.fine("validateCreditCardNumber - " + creditCardNumber + " -> " s_log.fine("validateCreditCardNumber - " + creditCardNumber + " -> "
+ ccNumber + ", Luhn=" + sum); + ccNumber + ", Luhn=" + sum);
return "CreditCardNumberError"; return "CreditCardNumberError";
} // validateCreditCardNumber } // validateCreditCardNumber
/** /**
* Validate Credit Card Number. * Validate Credit Card Number.
* - Check Card Type and Length * - Check Card Type and Length
* @param creditCardNumber CC Number * @param creditCardNumber CC Number
* @param creditCardType CC Type * @param creditCardType CC Type
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardNumber (String creditCardNumber, String creditCardType) public static String validateCreditCardNumber (String creditCardNumber, String creditCardType)
{ {
if (creditCardNumber == null || creditCardType == null) if (creditCardNumber == null || creditCardType == null)
return "CreditCardNumberError"; return "CreditCardNumberError";
// http://www.beachnet.com/~hstiles/cardtype.html // http://www.beachnet.com/~hstiles/cardtype.html
// http://staff.semel.fi/~kribe/document/luhn.htm // http://staff.semel.fi/~kribe/document/luhn.htm
String ccStartList = ""; // comma separated list of starting numbers String ccStartList = ""; // comma separated list of starting numbers
String ccLengthList = ""; // comma separated list of lengths String ccLengthList = ""; // comma separated list of lengths
// //
if (creditCardType.equals(MPayment.CREDITCARDTYPE_MasterCard)) if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard))
{ {
ccStartList = "51,52,53,54,55"; ccStartList = "51,52,53,54,55";
ccLengthList = "16"; ccLengthList = "16";
} }
else if (creditCardType.equals(MPayment.CREDITCARDTYPE_Visa)) else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa))
{ {
ccStartList = "4"; ccStartList = "4";
ccLengthList = "13,16"; ccLengthList = "13,16";
} }
else if (creditCardType.equals(MPayment.CREDITCARDTYPE_Amex)) else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex))
{ {
ccStartList = "34,37"; ccStartList = "34,37";
ccLengthList = "15"; ccLengthList = "15";
} }
else if (creditCardType.equals(MPayment.CREDITCARDTYPE_Discover)) else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Discover))
{ {
ccStartList = "6011"; ccStartList = "6011";
ccLengthList = "16"; ccLengthList = "16";
} }
else if (creditCardType.equals(MPayment.CREDITCARDTYPE_Diners)) else if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Diners))
{ {
ccStartList = "300,301,302,303,304,305,36,38"; ccStartList = "300,301,302,303,304,305,36,38";
ccLengthList = "14"; ccLengthList = "14";
} }
else else
{ {
// enRouteCard // enRouteCard
ccStartList = "2014,2149"; ccStartList = "2014,2149";
ccLengthList = "15"; ccLengthList = "15";
// JCBCard // JCBCard
ccStartList += ",3088,3096,3112,3158,3337,3528"; ccStartList += ",3088,3096,3112,3158,3337,3528";
ccLengthList += ",16"; ccLengthList += ",16";
// JCBCard // JCBCard
ccStartList += ",2131,1800"; ccStartList += ",2131,1800";
ccLengthList += ",15"; ccLengthList += ",15";
} }
// Clean up number // Clean up number
String ccNumber = checkNumeric(creditCardNumber); String ccNumber = checkNumeric(creditCardNumber);
/** /**
* Check Length * Check Length
*/ */
int ccLength = ccNumber.length(); int ccLength = ccNumber.length();
boolean ccLengthOK = false; boolean ccLengthOK = false;
StringTokenizer st = new StringTokenizer(ccLengthList, ",", false); StringTokenizer st = new StringTokenizer(ccLengthList, ",", false);
while (st.hasMoreTokens() && !ccLengthOK) while (st.hasMoreTokens() && !ccLengthOK)
{ {
int l = Integer.parseInt(st.nextToken()); int l = Integer.parseInt(st.nextToken());
if (ccLength == l) if (ccLength == l)
ccLengthOK = true; ccLengthOK = true;
} }
if (!ccLengthOK) if (!ccLengthOK)
{ {
s_log.fine("validateCreditCardNumber Length=" s_log.fine("validateCreditCardNumber Length="
+ ccLength + " <> " + ccLengthList); + ccLength + " <> " + ccLengthList);
return "CreditCardNumberError"; return "CreditCardNumberError";
} }
/** /**
* Check Start Digits * Check Start Digits
*/ */
boolean ccIdentified = false; boolean ccIdentified = false;
st = new StringTokenizer(ccStartList, ",", false); st = new StringTokenizer(ccStartList, ",", false);
while (st.hasMoreTokens() && !ccIdentified) while (st.hasMoreTokens() && !ccIdentified)
{ {
if (ccNumber.startsWith(st.nextToken())) if (ccNumber.startsWith(st.nextToken()))
ccIdentified = true; ccIdentified = true;
} }
if (!ccIdentified) if (!ccIdentified)
s_log.fine("validateCreditCardNumber Type=" s_log.fine("validateCreditCardNumber Type="
+ creditCardType + " <> " + ccStartList); + creditCardType + " <> " + ccStartList);
// //
String check = validateCreditCardNumber(ccNumber); String check = validateCreditCardNumber(ccNumber);
if (check.length() != 0) if (check.length() != 0)
return check; return check;
if (!ccIdentified) if (!ccIdentified)
return "CreditCardNumberProblem?"; return "CreditCardNumberProblem?";
return ""; return "";
} // validateCreditCardNumber } // validateCreditCardNumber
/** /**
* Validate Validation Code * Validate Validation Code
* @param creditCardVV CC Verification Code * @param creditCardVV CC Verification Code
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardVV (String creditCardVV) public static String validateCreditCardVV (String creditCardVV)
{ {
if (creditCardVV == null) if (creditCardVV == null)
return ""; return "";
int length = checkNumeric(creditCardVV).length(); int length = checkNumeric(creditCardVV).length();
if (length == 3 || length == 4) if (length == 3 || length == 4)
return ""; return "";
try try
{ {
Integer.parseInt (creditCardVV); Integer.parseInt (creditCardVV);
return ""; return "";
} }
catch (NumberFormatException ex) catch (NumberFormatException ex)
{ {
s_log.fine("validateCreditCardVV - " + ex); s_log.fine("validateCreditCardVV - " + ex);
} }
s_log.fine("validateCreditCardVV - length=" + length); s_log.fine("validateCreditCardVV - length=" + length);
return "CreditCardVVError"; return "CreditCardVVError";
} // validateCreditCardVV } // validateCreditCardVV
/** /**
* Validate Validation Code * Validate Validation Code
* @param creditCardVV CC Verification Code * @param creditCardVV CC Verification Code
* @param creditCardType CC Type see CC_ * @param creditCardType CC Type see CC_
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCreditCardVV (String creditCardVV, String creditCardType) public static String validateCreditCardVV (String creditCardVV, String creditCardType)
{ {
// no data // no data
if (creditCardVV == null || creditCardVV.length() == 0 if (creditCardVV == null || creditCardVV.length() == 0
|| creditCardType == null || creditCardType.length() == 0) || creditCardType == null || creditCardType.length() == 0)
return ""; return "";
int length = checkNumeric(creditCardVV).length(); int length = checkNumeric(creditCardVV).length();
// Amex = 4 digits // Amex = 4 digits
if (creditCardType.equals(MPayment.CREDITCARDTYPE_Amex)) if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Amex))
{ {
if (length == 4) if (length == 4)
{ {
try try
{ {
Integer.parseInt (creditCardVV); Integer.parseInt (creditCardVV);
return ""; return "";
} }
catch (NumberFormatException ex) catch (NumberFormatException ex)
{ {
s_log.fine("validateCreditCardVV - " + ex); s_log.fine("validateCreditCardVV - " + ex);
} }
} }
s_log.fine("validateCreditCardVV(4) CC=" + creditCardType + ", length=" + length); s_log.fine("validateCreditCardVV(4) CC=" + creditCardType + ", length=" + length);
return "CreditCardVVError"; return "CreditCardVVError";
} }
// Visa & MasterCard - 3 digits // Visa & MasterCard - 3 digits
if (creditCardType.equals(MPayment.CREDITCARDTYPE_Visa) if (creditCardType.equals(X_C_Payment.CREDITCARDTYPE_Visa)
|| creditCardType.equals(MPayment.CREDITCARDTYPE_MasterCard)) || creditCardType.equals(X_C_Payment.CREDITCARDTYPE_MasterCard))
{ {
if (length == 3) if (length == 3)
{ {
try try
{ {
Integer.parseInt (creditCardVV); Integer.parseInt (creditCardVV);
return ""; return "";
} }
catch (NumberFormatException ex) catch (NumberFormatException ex)
{ {
s_log.fine("validateCreditCardVV - " + ex); s_log.fine("validateCreditCardVV - " + ex);
} }
} }
s_log.fine("validateCreditCardVV(3) CC=" + creditCardType + ", length=" + length); s_log.fine("validateCreditCardVV(3) CC=" + creditCardType + ", length=" + length);
return "CreditCardVVError"; return "CreditCardVVError";
} }
// Other // Other
return ""; return "";
} // validateCreditCardVV } // validateCreditCardVV
/************************************************************************** /**************************************************************************
* Validate Routing Number * Validate Routing Number
* @param routingNo Routing No * @param routingNo Routing No
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateRoutingNo (String routingNo) public static String validateRoutingNo (String routingNo)
{ {
int length = checkNumeric(routingNo).length(); int length = checkNumeric(routingNo).length();
// US - length 9 // US - length 9
// Germany - length 8 // Germany - length 8
// Japan - 7 // Japan - 7
if (length == 7 || length == 8 || length == 9) // CH - 5
// Issue: Bank account country
if (length > 0)
return ""; return "";
return "PaymentBankRoutingNotValid"; return "PaymentBankRoutingNotValid";
} // validateBankRoutingNo } // validateBankRoutingNo
/** /**
* Validate Account No * Validate Account No
* @param AccountNo AccountNo * @param AccountNo AccountNo
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateAccountNo (String AccountNo) public static String validateAccountNo (String AccountNo)
{ {
int length = checkNumeric(AccountNo).length(); int length = checkNumeric(AccountNo).length();
if (length > 0) if (length > 0)
return ""; return "";
return "PaymentBankAccountNotValid"; return "PaymentBankAccountNotValid";
} // validateBankAccountNo } // validateBankAccountNo
/** /**
* Validate Check No * Validate Check No
* @param CheckNo CheckNo * @param CheckNo CheckNo
* @return "" or Error AD_Message * @return "" or Error AD_Message
*/ */
public static String validateCheckNo (String CheckNo) public static String validateCheckNo (String CheckNo)
{ {
int length = checkNumeric(CheckNo).length(); int length = checkNumeric(CheckNo).length();
if (length > 0) if (length > 0)
return ""; return "";
return "PaymentBankCheckNotValid"; return "PaymentBankCheckNotValid";
} // validateBankCheckNo } // validateBankCheckNo
/** /**
* Check Numeric * Check Numeric
* @param data input * @param data input
* @return the digits of the data - ignore the rest * @return the digits of the data - ignore the rest
*/ */
public static String checkNumeric (String data) public static String checkNumeric (String data)
{ {
if (data == null || data.length() == 0) if (data == null || data.length() == 0)
return ""; return "";
// Remove all non Digits // Remove all non Digits
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length(); i++) for (int i = 0; i < data.length(); i++)
{ {
if (Character.isDigit(data.charAt(i))) if (Character.isDigit(data.charAt(i)))
sb.append(data.charAt(i)); sb.append(data.charAt(i));
} }
return sb.toString(); return sb.toString();
} // checkNumeric } // checkNumeric
} // MPaymentValidate } // MPaymentValidate

File diff suppressed because it is too large Load Diff

View File

@ -3,27 +3,27 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
/** /**
* Scheduler Log * Scheduler Log
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MSchedulerLog.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: MSchedulerLog.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class MSchedulerLog extends X_AD_SchedulerLog public class MSchedulerLog extends X_AD_SchedulerLog
@ -31,37 +31,39 @@ public class MSchedulerLog extends X_AD_SchedulerLog
{ {
/** /**
* Standard Constructor * Standard Constructor
* @param ctx context * @param ctx context
* @param AD_SchedulerLog_ID id * @param AD_SchedulerLog_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MSchedulerLog (Properties ctx, int AD_SchedulerLog_ID, String trxName) public MSchedulerLog (Properties ctx, int AD_SchedulerLog_ID, String trxName)
{ {
super (ctx, AD_SchedulerLog_ID, trxName); super (ctx, AD_SchedulerLog_ID, trxName);
if (AD_SchedulerLog_ID == 0)
setIsError(false);
} // MSchedulerLog } // MSchedulerLog
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MSchedulerLog (Properties ctx, ResultSet rs, String trxName) public MSchedulerLog (Properties ctx, ResultSet rs, String trxName)
{ {
super(ctx, rs, trxName); super(ctx, rs, trxName);
} // MSchedulerLog } // MSchedulerLog
/** /**
* Parent Constructor * Parent Constructor
* @param parent parent * @param parent parent
* @param summary summary * @param summary summary
*/ */
public MSchedulerLog (MScheduler parent, String summary) public MSchedulerLog (MScheduler parent, String summary)
{ {
this (parent.getCtx(), 0, parent.get_TrxName()); this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent); setClientOrg(parent);
setAD_Scheduler_ID(parent.getAD_Scheduler_ID()); setAD_Scheduler_ID(parent.getAD_Scheduler_ID());
setSummary(summary); setSummary(summary);
} // MSchedulerLog } // MSchedulerLog
} // MSchedulerLog } // MSchedulerLog

View File

@ -3,50 +3,99 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.model; package org.compiere.model;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
/** /**
* Web Project Domain * Web Project Domain
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: MWebProjectDomain.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: MWebProjectDomain.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class MWebProjectDomain extends X_CM_WebProject_Domain public class MWebProjectDomain extends X_CM_WebProject_Domain
{ {
/** serialVersionUID */
private static final long serialVersionUID = 5134789895039452551L;
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MContainer.class);
/** /**
* Web Project Domain Constructor * Web Project Domain Constructor
* @param ctx context * @param ctx context
* @param CM_WebProject_Domain_ID id * @param CM_WebProject_Domain_ID id
* @param trxName transaction * @param trxName transaction
*/ */
public MWebProjectDomain (Properties ctx, int CM_WebProject_Domain_ID, String trxName) public MWebProjectDomain (Properties ctx, int CM_WebProject_Domain_ID, String trxName)
{ {
super (ctx, CM_WebProject_Domain_ID, trxName); super (ctx, CM_WebProject_Domain_ID, trxName);
} // MWebProjectDomain } // MWebProjectDomain
/** /**
* Load Constructor * Load Constructor
* @param ctx context * @param ctx context
* @param rs result set * @param rs result set
* @param trxName transaction * @param trxName transaction
*/ */
public MWebProjectDomain (Properties ctx, ResultSet rs, String trxName) public MWebProjectDomain (Properties ctx, ResultSet rs, String trxName)
{ {
super (ctx, rs, trxName); super (ctx, rs, trxName);
} // MWebProjectDomain } // MWebProjectDomain
/**
* get WebProjectDomain by Name
* @param ctx
* @param ServerName
* @param trxName
* @return ContainerElement
*/
public static MWebProjectDomain get(Properties ctx, String ServerName, String trxName) {
MWebProjectDomain thisWebProjectDomain = null;
String sql = "SELECT * FROM CM_WebProject_Domain WHERE lower(FQDN) LIKE ? ORDER by CM_WebProject_Domain_ID DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setString(1, ServerName);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
thisWebProjectDomain = (new MWebProjectDomain(ctx, rs, trxName));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return thisWebProjectDomain;
}
} // MWebProjectDomain } // MWebProjectDomain

View File

@ -3,78 +3,78 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.process; package org.compiere.process;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.print.*; import org.compiere.print.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Dunning Letter Print * Dunning Letter Print
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: DunningPrint.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: DunningPrint.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class DunningPrint extends SvrProcess public class DunningPrint extends SvrProcess
{ {
/** Mail PDF */ /** Mail PDF */
private boolean p_EMailPDF = false; private boolean p_EMailPDF = false;
/** Mail Template */ /** Mail Template */
private int p_R_MailText_ID = 0; private int p_R_MailText_ID = 0;
/** Dunning Run */ /** Dunning Run */
private int p_C_DunningRun_ID = 0; private int p_C_DunningRun_ID = 0;
/** Print only Outstanding */ /** Print only Outstanding */
private boolean p_IsOnlyIfBPBalance = true; private boolean p_IsOnlyIfBPBalance = true;
/** /**
* Prepare - e.g., get Parameters. * Prepare - e.g., get Parameters.
*/ */
protected void prepare() protected void prepare()
{ {
ProcessInfoParameter[] para = getParameter(); ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++) for (int i = 0; i < para.length; i++)
{ {
String name = para[i].getParameterName(); String name = para[i].getParameterName();
if (para[i].getParameter() == null) if (para[i].getParameter() == null)
; ;
else if (name.equals("EMailPDF")) else if (name.equals("EMailPDF"))
p_EMailPDF = "Y".equals(para[i].getParameter()); p_EMailPDF = "Y".equals(para[i].getParameter());
else if (name.equals("R_MailText_ID")) else if (name.equals("R_MailText_ID"))
p_R_MailText_ID = para[i].getParameterAsInt(); p_R_MailText_ID = para[i].getParameterAsInt();
else if (name.equals("C_DunningRun_ID")) else if (name.equals("C_DunningRun_ID"))
p_C_DunningRun_ID = para[i].getParameterAsInt(); p_C_DunningRun_ID = para[i].getParameterAsInt();
else if (name.equals("IsOnlyIfBPBalance")) else if (name.equals("IsOnlyIfBPBalance"))
p_IsOnlyIfBPBalance = "Y".equals(para[i].getParameter()); p_IsOnlyIfBPBalance = "Y".equals(para[i].getParameter());
else else
log.log(Level.SEVERE, "Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
} // prepare } // prepare
/** /**
* Pocess * Pocess
* @return info * @return info
* @throws Exception * @throws Exception
*/ */
protected String doIt () throws Exception protected String doIt () throws Exception
{ {
log.info("C_DunningRun_ID=" + p_C_DunningRun_ID + ",R_MailText_ID=" + p_R_MailText_ID log.info("C_DunningRun_ID=" + p_C_DunningRun_ID + ",R_MailText_ID=" + p_R_MailText_ID
+ ", EmailPDF=" + p_EMailPDF + ",IsOnlyIfBPBalance=" + p_IsOnlyIfBPBalance); + ", EmailPDF=" + p_EMailPDF + ",IsOnlyIfBPBalance=" + p_IsOnlyIfBPBalance);
// Need to have Template // Need to have Template
if (p_EMailPDF && p_R_MailText_ID == 0) if (p_EMailPDF && p_R_MailText_ID == 0)
@ -95,122 +95,127 @@ public class DunningPrint extends SvrProcess
// Print Format on Dunning Level // Print Format on Dunning Level
MDunningLevel level = new MDunningLevel (getCtx(), run.getC_DunningLevel_ID(), get_TrxName()); MDunningLevel level = new MDunningLevel (getCtx(), run.getC_DunningLevel_ID(), get_TrxName());
MPrintFormat format = MPrintFormat.get (getCtx(), level.getDunning_PrintFormat_ID(), false); MPrintFormat format = MPrintFormat.get (getCtx(), level.getDunning_PrintFormat_ID(), false);
MClient client = MClient.get(getCtx()); MClient client = MClient.get(getCtx());
int count = 0; int count = 0;
int errors = 0; int errors = 0;
MDunningRunEntry[] entries = run.getEntries(false); MDunningRunEntry[] entries = run.getEntries(false);
for (int i = 0; i < entries.length; i++) for (int i = 0; i < entries.length; i++)
{ {
MDunningRunEntry entry = entries[i]; MDunningRunEntry entry = entries[i];
if (p_IsOnlyIfBPBalance && entry.getAmt().signum() <= 0) if (p_IsOnlyIfBPBalance && entry.getAmt().signum() <= 0)
continue; continue;
// To BPartner // To BPartner
MBPartner bp = new MBPartner (getCtx(), entry.getC_BPartner_ID(), get_TrxName()); MBPartner bp = new MBPartner (getCtx(), entry.getC_BPartner_ID(), get_TrxName());
if (bp.get_ID() == 0) if (bp.get_ID() == 0)
{ {
addLog (entry.get_ID(), null, null, "@NotFound@: @C_BPartner_ID@ " + entry.getC_BPartner_ID()); addLog (entry.get_ID(), null, null, "@NotFound@: @C_BPartner_ID@ " + entry.getC_BPartner_ID());
errors++; errors++;
continue; continue;
} }
// To User // To User
MUser to = new MUser (getCtx(), entry.getAD_User_ID(), get_TrxName()); MUser to = new MUser (getCtx(), entry.getAD_User_ID(), get_TrxName());
if (p_EMailPDF) if (p_EMailPDF)
{ {
if (to.get_ID() == 0) if (to.get_ID() == 0)
{ {
addLog (entry.get_ID(), null, null, "@NotFound@: @AD_User_ID@ - " + bp.getName()); addLog (entry.get_ID(), null, null, "@NotFound@: @AD_User_ID@ - " + bp.getName());
errors++; errors++;
continue; continue;
} }
else if (to.getEMail() == null || to.getEMail().length() == 0) else if (to.getEMail() == null || to.getEMail().length() == 0)
{ {
addLog (entry.get_ID(), null, null, "@NotFound@: @EMail@ - " + to.getName()); addLog (entry.get_ID(), null, null, "@NotFound@: @EMail@ - " + to.getName());
errors++; errors++;
continue; continue;
} }
} }
// BP Language // BP Language
Language language = Language.getLoginLanguage(); // Base Language Language language = Language.getLoginLanguage(); // Base Language
String tableName = "C_Dunning_Header_v"; String tableName = "C_Dunning_Header_v";
if (client.isMultiLingualDocument()) if (client.isMultiLingualDocument())
{ {
tableName += "t"; tableName += "t";
String AD_Language = bp.getAD_Language(); String AD_Language = bp.getAD_Language();
if (AD_Language != null) if (AD_Language != null)
language = Language.getLanguage(AD_Language); language = Language.getLanguage(AD_Language);
} }
format.setLanguage(language); format.setLanguage(language);
format.setTranslationLanguage(language); format.setTranslationLanguage(language);
// query // query
MQuery query = new MQuery(tableName); MQuery query = new MQuery(tableName);
query.addRestriction("C_DunningRunEntry_ID", MQuery.EQUAL, query.addRestriction("C_DunningRunEntry_ID", MQuery.EQUAL,
new Integer(entry.getC_DunningRunEntry_ID())); new Integer(entry.getC_DunningRunEntry_ID()));
// Engine // Engine
PrintInfo info = new PrintInfo( PrintInfo info = new PrintInfo(
bp.getName(), bp.getName(),
X_C_DunningRunEntry.Table_ID, X_C_DunningRunEntry.Table_ID,
entry.getC_DunningRunEntry_ID(), entry.getC_DunningRunEntry_ID(),
entry.getC_BPartner_ID()); entry.getC_BPartner_ID());
info.setDescription(bp.getName() + ", Amt=" + entry.getAmt()); info.setDescription(bp.getName() + ", Amt=" + entry.getAmt());
ReportEngine re = new ReportEngine(getCtx(), format, query, info); ReportEngine re = new ReportEngine(getCtx(), format, query, info);
boolean printed = false; boolean printed = false;
if (p_EMailPDF) if (p_EMailPDF)
{ {
EMail email = client.createEMail(to.getEMail(), null, null); EMail email = client.createEMail(to.getEMail(), null, null);
if (!email.isValid()) if (!email.isValid())
{ {
addLog (entry.get_ID(), null, null, addLog (entry.get_ID(), null, null,
"@RequestActionEMailError@ Invalid EMail: " + to); "@RequestActionEMailError@ Invalid EMail: " + to);
errors++; errors++;
continue; continue;
} }
mText.setUser(to); // variable context mText.setUser(to); // variable context
mText.setBPartner(bp); mText.setBPartner(bp);
mText.setPO(entry); mText.setPO(entry);
String message = mText.getMailText(true); String message = mText.getMailText(true);
if (mText.isHtml()) if (mText.isHtml())
email.setMessageHTML(mText.getMailHeader(), message); email.setMessageHTML(mText.getMailHeader(), message);
else else
{ {
email.setSubject (mText.getMailHeader()); email.setSubject (mText.getMailHeader());
email.setMessageText (message); email.setMessageText (message);
} }
// //
File attachment = re.getPDF(File.createTempFile("Dunning", ".pdf")); File attachment = re.getPDF(File.createTempFile("Dunning", ".pdf"));
log.fine(to + " - " + attachment); log.fine(to + " - " + attachment);
email.addAttachment(attachment); email.addAttachment(attachment);
// //
String msg = email.send(); String msg = email.send();
MUserMail um = new MUserMail(mText, entry.getAD_User_ID(), email); MUserMail um = new MUserMail(mText, entry.getAD_User_ID(), email);
um.save(); um.save();
if (msg.equals(EMail.SENT_OK)) if (msg.equals(EMail.SENT_OK))
{ {
addLog (entry.get_ID(), null, null, addLog (entry.get_ID(), null, null,
bp.getName() + " @RequestActionEMailOK@"); bp.getName() + " @RequestActionEMailOK@");
count++; count++;
printed = true; printed = true;
} }
else else
{ {
addLog (entry.get_ID(), null, null, addLog (entry.get_ID(), null, null,
bp.getName() + " @RequestActionEMailError@ " + msg); bp.getName() + " @RequestActionEMailError@ " + msg);
errors++; errors++;
} }
} }
else else
{ {
re.print (); re.print ();
count++; count++;
printed = true; printed = true;
} }
if (printed)
{
entry.setProcessed (true);
entry.save ();
}
} // for all dunning letters } // for all dunning letters
if (p_EMailPDF) if (p_EMailPDF)
return "@Sent@=" + count + " - @Errors@=" + errors; return "@Sent@=" + count + " - @Errors@=" + errors;
return "@Printed@=" + count; return "@Printed@=" + count;
} // doIt } // doIt
} // DunningPrint } // DunningPrint

View File

@ -3,350 +3,395 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.process; package org.compiere.process;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Create Dunning Run Entries/Lines * Create Dunning Run Entries/Lines
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: DunningRunCreate.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: DunningRunCreate.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class DunningRunCreate extends SvrProcess public class DunningRunCreate extends SvrProcess
{ {
private boolean p_IncludeInDispute = false; private boolean p_IncludeInDispute = false;
private boolean p_OnlySOTrx = false; private boolean p_OnlySOTrx = false;
private boolean p_IsAllCurrencies = false;
private int p_SalesRep_ID = 0; private int p_SalesRep_ID = 0;
private int p_C_Currency_ID = 0; private int p_C_Currency_ID = 0;
private int p_C_BPartner_ID = 0; private int p_C_BPartner_ID = 0;
private int p_C_BP_Group_ID = 0; private int p_C_BP_Group_ID = 0;
private int p_C_DunningRun_ID = 0; private int p_C_DunningRun_ID = 0;
private MDunningRun m_run = null; private MDunningRun m_run = null;
private MDunningLevel m_level = null;
/** /**
* Prepare - e.g., get Parameters. * Prepare - e.g., get Parameters.
*/ */
protected void prepare() protected void prepare()
{ {
ProcessInfoParameter[] para = getParameter(); ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++) for (int i = 0; i < para.length; i++)
{ {
String name = para[i].getParameterName(); String name = para[i].getParameterName();
if (para[i].getParameter() == null) if (para[i].getParameter() == null)
; ;
else if (name.equals("IncludeInDispute")) else if (name.equals("IncludeInDispute"))
p_IncludeInDispute = "Y".equals(para[i].getParameter()); p_IncludeInDispute = "Y".equals(para[i].getParameter());
else if (name.equals("OnlySOTrx")) else if (name.equals("OnlySOTrx"))
p_OnlySOTrx = "Y".equals(para[i].getParameter()); p_OnlySOTrx = "Y".equals(para[i].getParameter());
else if (name.equals("IsAllCurrencies"))
p_IsAllCurrencies = "Y".equals(para[i].getParameter());
else if (name.equals("SalesRep_ID")) else if (name.equals("SalesRep_ID"))
p_SalesRep_ID = para[i].getParameterAsInt(); p_SalesRep_ID = para[i].getParameterAsInt();
else if (name.equals("C_Currency_ID")) else if (name.equals("C_Currency_ID"))
p_C_Currency_ID = para[i].getParameterAsInt(); p_C_Currency_ID = para[i].getParameterAsInt();
else if (name.equals("C_BPartner_ID")) else if (name.equals("C_BPartner_ID"))
p_C_BPartner_ID = para[i].getParameterAsInt(); p_C_BPartner_ID = para[i].getParameterAsInt();
else if (name.equals("C_BP_Group_ID")) else if (name.equals("C_BP_Group_ID"))
p_C_BP_Group_ID = para[i].getParameterAsInt(); p_C_BP_Group_ID = para[i].getParameterAsInt();
else else
log.log(Level.SEVERE, "Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
p_C_DunningRun_ID = getRecord_ID(); p_C_DunningRun_ID = getRecord_ID();
} // prepare } // prepare
/** /**
* Process * Process
* @return message * @return message
* @throws Exception * @throws Exception
*/ */
protected String doIt () throws Exception protected String doIt () throws Exception
{ {
log.info("C_DunningRun_ID=" + p_C_DunningRun_ID log.info("C_DunningRun_ID=" + p_C_DunningRun_ID
+ ", Dispute=" + p_IncludeInDispute + ", Dispute=" + p_IncludeInDispute
+ ", C_BP_Group_ID=" + p_C_BP_Group_ID + ", C_BP_Group_ID=" + p_C_BP_Group_ID
+ ", C_BPartner_ID=" + p_C_BPartner_ID); + ", C_BPartner_ID=" + p_C_BPartner_ID);
m_run = new MDunningRun (getCtx(),p_C_DunningRun_ID, get_TrxName()); m_run = new MDunningRun (getCtx(),p_C_DunningRun_ID, get_TrxName());
if (m_run.get_ID() == 0) if (m_run.get_ID() == 0)
throw new IllegalArgumentException ("Not found MDunningRun"); throw new IllegalArgumentException ("Not found MDunningRun");
if (!m_run.deleteEntries(true)) if (!m_run.deleteEntries(true))
throw new IllegalArgumentException ("Cannot delete existing entries"); throw new IllegalArgumentException ("Cannot delete existing entries");
if (p_SalesRep_ID == 0) if (p_SalesRep_ID == 0)
throw new IllegalArgumentException ("No SalesRep"); throw new IllegalArgumentException ("No SalesRep");
if (p_C_Currency_ID == 0) if (p_C_Currency_ID == 0)
throw new IllegalArgumentException ("No Currency"); throw new IllegalArgumentException ("No Currency");
// //
m_level = m_run.getLevel ();
int inv = addInvoices(); int inv = addInvoices();
int pay = addPayments(); int pay = addPayments();
if (m_level.isChargeFee ())
addFees();
return "@C_Invoice_ID@ #" + inv + " - @C_Payment_ID@=" + pay; return "@C_Invoice_ID@ #" + inv + " - @C_Payment_ID@=" + pay;
} // doIt } // doIt
/************************************************************************** /**************************************************************************
* Add Invoices to Run * Add Invoices to Run
* @return no of invoices * @return no of invoices
*/ */
private int addInvoices() private int addInvoices()
{ {
int count = 0; int count = 0;
String sql = "SELECT i.C_Invoice_ID, i.C_Currency_ID," String sql = "SELECT i.C_Invoice_ID, i.C_Currency_ID,"
+ " i.GrandTotal*i.MultiplierAP," + " i.GrandTotal*i.MultiplierAP,"
+ " invoiceOpen(i.C_Invoice_ID,i.C_InvoicePaySchedule_ID)*MultiplierAP," + " invoiceOpen(i.C_Invoice_ID,i.C_InvoicePaySchedule_ID)*MultiplierAP,"
+ " COALESCE(daysBetween(?,ips.DueDate),paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced,?))," // ##1/2 + " COALESCE(daysBetween(?,ips.DueDate),paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced,?))," // ##1/2
+ " i.IsInDispute, i.C_BPartner_ID " + " i.IsInDispute, i.C_BPartner_ID "
+ "FROM C_Invoice_v i " + "FROM C_Invoice_v i "
+ " LEFT OUTER JOIN C_InvoicePaySchedule ips ON (i.C_InvoicePaySchedule_ID=ips.C_InvoicePaySchedule_ID) " + " LEFT OUTER JOIN C_InvoicePaySchedule ips ON (i.C_InvoicePaySchedule_ID=ips.C_InvoicePaySchedule_ID) "
+ "WHERE i.IsPaid='N' AND i.AD_Client_ID=?" // ##3 + "WHERE i.IsPaid='N' AND i.AD_Client_ID=?" // ##3
+ " AND i.DocStatus IN ('CO','CL')" + " AND i.DocStatus IN ('CO','CL')"
// Only BP(Group) with Dunning defined // Only BP(Group) with Dunning defined
+ " AND EXISTS (SELECT * FROM C_DunningLevel dl " + " AND EXISTS (SELECT * FROM C_DunningLevel dl "
+ "WHERE dl.C_DunningLevel_ID=?" // // ##4 + "WHERE dl.C_DunningLevel_ID=?" // // ##4
+ " AND dl.C_Dunning_ID IN " + " AND dl.C_Dunning_ID IN "
+ "(SELECT COALESCE(bp.C_Dunning_ID, bpg.C_Dunning_ID) " + "(SELECT COALESCE(bp.C_Dunning_ID, bpg.C_Dunning_ID) "
+ "FROM C_BPartner bp" + "FROM C_BPartner bp"
+ " INNER JOIN C_BP_Group bpg ON (bp.C_BP_Group_ID=bpg.C_BP_Group_ID) " + " INNER JOIN C_BP_Group bpg ON (bp.C_BP_Group_ID=bpg.C_BP_Group_ID) "
+ "WHERE i.C_BPartner_ID=bp.C_BPartner_ID))"; + "WHERE i.C_BPartner_ID=bp.C_BPartner_ID))";
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
sql += " AND i.C_BPartner_ID=?"; // ##5 sql += " AND i.C_BPartner_ID=?"; // ##5
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
sql += " AND EXISTS (SELECT * FROM C_BPartner bp " sql += " AND EXISTS (SELECT * FROM C_BPartner bp "
+ "WHERE i.C_BPartner_ID=bp.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ##5 + "WHERE i.C_BPartner_ID=bp.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ##5
if (p_OnlySOTrx) if (p_OnlySOTrx)
sql += " AND i.IsSOTrx='Y'"; sql += " AND i.IsSOTrx='Y'";
if (!p_IsAllCurrencies)
sql += " AND i.C_Currency_ID=" + p_C_Currency_ID;
// log.info(sql); // log.info(sql);
// Sub Query String sql2=null;
String sql2 = "SELECT COUNT(*), COALESCE(TRUNC(SysDate-MAX(dr.DunningDate)),0) "
// if sequentially we must check for other levels with smaller days for
// which this invoice is not yet included!
if (m_level.getParent ().isCreateLevelsSequentially ()) {
// Build a list of all topmost Dunning Levels
MDunningLevel[] previousLevels = m_level.getPreviousLevels();
if (previousLevels!=null && previousLevels.length>0) {
String sqlAppend = "";
for (int i=0; i<previousLevels.length; i++)
{
sqlAppend += " AND i.C_Invoice_ID IN (SELECT C_Invoice_ID FROM C_DunningRunLine WHERE " +
"C_DunningRunEntry_ID IN (SELECT C_DunningRunEntry_ID FROM C_DunningRunEntry WHERE " +
"C_DunningRun_ID IN (SELECT C_DunningRun_ID FROM C_DunningRun WHERE " +
"C_DunningLevel_ID=" + previousLevels[i].get_ID () + ")) AND Processed<>'N')";
}
sql += sqlAppend;
}
}
sql2 = "SELECT COUNT(*), COALESCE(TRUNC(SysDate-MAX(dr.DunningDate)),0) "
+ "FROM C_DunningRun dr" + "FROM C_DunningRun dr"
+ " INNER JOIN C_DunningRunEntry dre ON (dr.C_DunningRun_ID=dre.C_DunningRun_ID)" + " INNER JOIN C_DunningRunEntry dre ON (dr.C_DunningRun_ID=dre.C_DunningRun_ID)"
+ " INNER JOIN C_DunningRunLine drl ON (dre.C_DunningRunEntry_ID=drl.C_DunningRunEntry_ID) " + " INNER JOIN C_DunningRunLine drl ON (dre.C_DunningRunEntry_ID=drl.C_DunningRunEntry_ID) "
+ "WHERE drl.Processed='Y' AND drl.C_Invoice_ID=?"; + "WHERE drl.Processed='Y' AND drl.C_Invoice_ID=?";
BigDecimal DaysAfterDue = m_run.getLevel().getDaysAfterDue(); BigDecimal DaysAfterDue = m_run.getLevel().getDaysAfterDue();
int DaysBetweenDunning = m_run.getLevel().getDaysBetweenDunning(); int DaysBetweenDunning = m_run.getLevel().getDaysBetweenDunning();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null; PreparedStatement pstmt2 = null;
try try
{ {
pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setTimestamp(1, m_run.getDunningDate()); pstmt.setTimestamp(1, m_run.getDunningDate());
pstmt.setTimestamp(2, m_run.getDunningDate()); pstmt.setTimestamp(2, m_run.getDunningDate());
pstmt.setInt (3, m_run.getAD_Client_ID()); pstmt.setInt (3, m_run.getAD_Client_ID());
pstmt.setInt(4, m_run.getC_DunningLevel_ID()); pstmt.setInt(4, m_run.getC_DunningLevel_ID());
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
pstmt.setInt (5, p_C_BPartner_ID); pstmt.setInt (5, p_C_BPartner_ID);
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
pstmt.setInt (5, p_C_BP_Group_ID); pstmt.setInt (5, p_C_BP_Group_ID);
// //
pstmt2 = DB.prepareStatement (sql2, get_TrxName()); pstmt2 = DB.prepareStatement (sql2, get_TrxName());
// //
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
int C_Invoice_ID = rs.getInt(1); int C_Invoice_ID = rs.getInt(1);
int C_Currency_ID = rs.getInt(2); int C_Currency_ID = rs.getInt(2);
BigDecimal GrandTotal = rs.getBigDecimal(3); BigDecimal GrandTotal = rs.getBigDecimal(3);
BigDecimal Open = rs.getBigDecimal(4); BigDecimal Open = rs.getBigDecimal(4);
int DaysDue = rs.getInt(5); int DaysDue = rs.getInt(5);
boolean IsInDispute = "Y".equals(rs.getString(6)); boolean IsInDispute = "Y".equals(rs.getString(6));
int C_BPartner_ID = rs.getInt(7); int C_BPartner_ID = rs.getInt(7);
// //
if (!p_IncludeInDispute && IsInDispute) if (!p_IncludeInDispute && IsInDispute)
continue; continue;
if (DaysDue < DaysAfterDue.intValue()) if (DaysDue < DaysAfterDue.intValue() && !m_level.isShowAllDue ())
continue; continue;
if (Env.ZERO.compareTo(Open) == 0) if (Env.ZERO.compareTo(Open) == 0)
continue; continue;
// //
int TimesDunned = 0; int TimesDunned = 0;
int DaysAfterLast = 0; int DaysAfterLast = 0;
// SubQuery // SubQuery
pstmt2.setInt (1, C_Invoice_ID); pstmt2.setInt (1, C_Invoice_ID);
ResultSet rs2 = pstmt2.executeQuery (); ResultSet rs2 = pstmt2.executeQuery ();
if (rs2.next()) if (rs2.next())
{ {
TimesDunned = rs2.getInt(1); TimesDunned = rs2.getInt(1);
DaysAfterLast = rs2.getInt(2); DaysAfterLast = rs2.getInt(2);
} }
rs2.close(); rs2.close();
// SubQuery // SubQuery
if (DaysBetweenDunning != 0 && DaysAfterLast < DaysBetweenDunning)
if (DaysBetweenDunning != 0 && DaysAfterLast < DaysBetweenDunning && !m_level.isShowAllDue () && !m_level.isShowNotDue ())
continue; continue;
// //
createInvoiceLine (C_Invoice_ID, C_Currency_ID, GrandTotal, Open, createInvoiceLine (C_Invoice_ID, C_Currency_ID, GrandTotal, Open,
DaysDue, IsInDispute, C_BPartner_ID, DaysDue, IsInDispute, C_BPartner_ID,
TimesDunned, DaysAfterLast); TimesDunned, DaysAfterLast);
count++; count++;
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
pstmt2.close(); pstmt2.close();
pstmt2 = null; pstmt2 = null;
} }
catch (Exception e) catch (Exception e)
{ {
log.log(Level.SEVERE, "addInvoices", e); log.log(Level.SEVERE, "addInvoices", e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
if (pstmt2 != null) if (pstmt2 != null)
pstmt2.close (); pstmt2.close ();
pstmt = null; pstmt = null;
pstmt2 = null; pstmt2 = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
pstmt2 = null; pstmt2 = null;
} }
return count; return count;
} // addInvoices } // addInvoices
/** /**
* Create Invoice Line * Create Invoice Line
* @param C_Invoice_ID * @param C_Invoice_ID
* @param C_Currency_ID * @param C_Currency_ID
* @param GrandTotal * @param GrandTotal
* @param Open * @param Open
* @param DaysDue * @param DaysDue
* @param IsInDispute * @param IsInDispute
* @param C_BPartner_ID * @param C_BPartner_ID
* @param TimesDunned * @param TimesDunned
* @param DaysAfterLast * @param DaysAfterLast
*/ */
private void createInvoiceLine (int C_Invoice_ID, int C_Currency_ID, private void createInvoiceLine (int C_Invoice_ID, int C_Currency_ID,
BigDecimal GrandTotal, BigDecimal Open, BigDecimal GrandTotal, BigDecimal Open,
int DaysDue, boolean IsInDispute, int DaysDue, boolean IsInDispute,
int C_BPartner_ID, int TimesDunned, int DaysAfterLast) int C_BPartner_ID, int TimesDunned, int DaysAfterLast)
{ {
MDunningRunEntry entry = m_run.getEntry (C_BPartner_ID, p_C_Currency_ID, p_SalesRep_ID); MDunningRunEntry entry = m_run.getEntry (C_BPartner_ID, p_C_Currency_ID, p_SalesRep_ID);
if (entry.get_ID() == 0) if (entry.get_ID() == 0)
if (!entry.save()) if (!entry.save())
throw new IllegalStateException("Cannot save MDunningRunEntry"); throw new IllegalStateException("Cannot save MDunningRunEntry");
// //
MDunningRunLine line = new MDunningRunLine (entry); MDunningRunLine line = new MDunningRunLine (entry);
line.setInvoice(C_Invoice_ID, C_Currency_ID, GrandTotal, Open, line.setInvoice(C_Invoice_ID, C_Currency_ID, GrandTotal, Open,
DaysDue, IsInDispute, TimesDunned, DaysAfterLast); new BigDecimal(0), DaysDue, IsInDispute, TimesDunned,
DaysAfterLast);
if (!line.save()) if (!line.save())
throw new IllegalStateException("Cannot save MDunningRunLine"); throw new IllegalStateException("Cannot save MDunningRunLine");
} // createInvoiceLine } // createInvoiceLine
/************************************************************************** /**************************************************************************
* Add Payments to Run * Add Payments to Run
* @return no of payments * @return no of payments
*/ */
private int addPayments() private int addPayments()
{ {
String sql = "SELECT C_Payment_ID, C_Currency_ID, PayAmt," String sql = "SELECT C_Payment_ID, C_Currency_ID, PayAmt,"
+ " paymentAvailable(C_Payment_ID), C_BPartner_ID " + " paymentAvailable(C_Payment_ID), C_BPartner_ID "
+ "FROM C_Payment_v p " + "FROM C_Payment_v p "
+ "WHERE AD_Client_ID=?" // ##1 + "WHERE AD_Client_ID=?" // ##1
+ " AND IsAllocated='N' AND C_BPartner_ID IS NOT NULL" + " AND IsAllocated='N' AND C_BPartner_ID IS NOT NULL"
+ " AND C_Charge_ID IS NULL" + " AND C_Charge_ID IS NULL"
+ " AND DocStatus IN ('CO','CL')" + " AND DocStatus IN ('CO','CL')"
// Only BP with Dunning defined // Only BP with Dunning defined
+ " AND EXISTS (SELECT * FROM C_BPartner bp " + " AND EXISTS (SELECT * FROM C_BPartner bp "
+ "WHERE p.C_BPartner_ID=bp.C_BPartner_ID" + "WHERE p.C_BPartner_ID=bp.C_BPartner_ID"
+ " AND bp.C_Dunning_ID=(SELECT C_Dunning_ID FROM C_DunningLevel WHERE C_DunningLevel_ID=?))"; // ##2 + " AND bp.C_Dunning_ID=(SELECT C_Dunning_ID FROM C_DunningLevel WHERE C_DunningLevel_ID=?))"; // ##2
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
sql += " AND C_BPartner_ID=?"; // ##3 sql += " AND C_BPartner_ID=?"; // ##3
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
sql += " AND EXISTS (SELECT * FROM C_BPartner bp " sql += " AND EXISTS (SELECT * FROM C_BPartner bp "
+ "WHERE p.C_BPartner_ID=bp.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ##3 + "WHERE p.C_BPartner_ID=bp.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ##3
if (p_OnlySOTrx) if (p_OnlySOTrx)
sql += " AND IsReceipt='Y'"; sql += " AND IsReceipt='Y'";
int count = 0; int count = 0;
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getAD_Client_ID()); pstmt.setInt (1, getAD_Client_ID());
pstmt.setInt (2, m_run.getC_DunningLevel_ID()); pstmt.setInt (2, m_run.getC_DunningLevel_ID());
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
pstmt.setInt (3, p_C_BPartner_ID); pstmt.setInt (3, p_C_BPartner_ID);
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
pstmt.setInt (3, p_C_BP_Group_ID); pstmt.setInt (3, p_C_BP_Group_ID);
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
int C_Payment_ID = rs.getInt(1); int C_Payment_ID = rs.getInt(1);
int C_Currency_ID = rs.getInt(2); int C_Currency_ID = rs.getInt(2);
BigDecimal PayAmt = rs.getBigDecimal(3).negate(); BigDecimal PayAmt = rs.getBigDecimal(3).negate();
BigDecimal OpenAmt = rs.getBigDecimal(4).negate(); BigDecimal OpenAmt = rs.getBigDecimal(4).negate();
int C_BPartner_ID = rs.getInt(5); int C_BPartner_ID = rs.getInt(5);
// //
if (Env.ZERO.compareTo(OpenAmt) == 0) if (Env.ZERO.compareTo(OpenAmt) == 0)
continue; continue;
// //
createPaymentLine (C_Payment_ID, C_Currency_ID, PayAmt, OpenAmt, createPaymentLine (C_Payment_ID, C_Currency_ID, PayAmt, OpenAmt,
C_BPartner_ID); C_BPartner_ID);
count++; count++;
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
log.log(Level.SEVERE, sql, e); log.log(Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
return count; return count;
} // addPayments } // addPayments
/** /**
* Create Payment Line * Create Payment Line
* @param C_Payment_ID * @param C_Payment_ID
* @param C_Currency_ID * @param C_Currency_ID
* @param PayAmt * @param PayAmt
* @param OpenAmt * @param OpenAmt
* @param C_BPartner_ID * @param C_BPartner_ID
*/ */
private void createPaymentLine (int C_Payment_ID, int C_Currency_ID, private void createPaymentLine (int C_Payment_ID, int C_Currency_ID,
BigDecimal PayAmt, BigDecimal OpenAmt, int C_BPartner_ID) BigDecimal PayAmt, BigDecimal OpenAmt, int C_BPartner_ID)
{ {
MDunningRunEntry entry = m_run.getEntry (C_BPartner_ID, p_C_Currency_ID, p_SalesRep_ID); MDunningRunEntry entry = m_run.getEntry (C_BPartner_ID, p_C_Currency_ID, p_SalesRep_ID);
if (entry.get_ID() == 0) if (entry.get_ID() == 0)
if (!entry.save()) if (!entry.save())
throw new IllegalStateException("Cannot save MDunningRunEntry"); throw new IllegalStateException("Cannot save MDunningRunEntry");
// //
MDunningRunLine line = new MDunningRunLine (entry); MDunningRunLine line = new MDunningRunLine (entry);
line.setPayment(C_Payment_ID, C_Currency_ID, PayAmt, OpenAmt); line.setPayment(C_Payment_ID, C_Currency_ID, PayAmt, OpenAmt);
if (!line.save()) if (!line.save())
throw new IllegalStateException("Cannot save MDunningRunLine"); throw new IllegalStateException("Cannot save MDunningRunLine");
} // createPaymentLine } // createPaymentLine
private void addFees()
{
MDunningRunEntry [] entries = m_run.getEntries (true);
if (entries!=null && entries.length>0) {
for (int i=0;i<entries.length;i++) {
MDunningRunLine line = new MDunningRunLine (entries[i]);
line.setFee (p_C_Currency_ID, m_level.getFeeAmt ());
if (!line.save())
throw new IllegalStateException("Cannot save MDunningRunLine");
entries[i].setQty (entries[i].getQty ().subtract (new BigDecimal(1)));
}
}
}
} // DunningRunCreate } // DunningRunCreate

View File

@ -3,13 +3,13 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
@ -17,511 +17,511 @@
*****************************************************************************/ *****************************************************************************/
package org.compiere.process; package org.compiere.process;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Import BPartners from I_BPartner * Import BPartners from I_BPartner
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: ImportBPartner.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: ImportBPartner.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class ImportBPartner extends SvrProcess public class ImportBPartner extends SvrProcess
{ {
/** Client to be imported to */ /** Client to be imported to */
private int m_AD_Client_ID = 0; private int m_AD_Client_ID = 0;
/** Delete old Imported */ /** Delete old Imported */
private boolean m_deleteOldImported = false; private boolean m_deleteOldImported = false;
/** Organization to be imported to */ /** Organization to be imported to */
private int m_AD_Org_ID = 0; private int m_AD_Org_ID = 0;
/** Effective */ /** Effective */
private Timestamp m_DateValue = null; private Timestamp m_DateValue = null;
/** /**
* Prepare - e.g., get Parameters. * Prepare - e.g., get Parameters.
*/ */
protected void prepare() protected void prepare()
{ {
ProcessInfoParameter[] para = getParameter(); ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++) for (int i = 0; i < para.length; i++)
{ {
String name = para[i].getParameterName(); String name = para[i].getParameterName();
if (name.equals("AD_Client_ID")) if (name.equals("AD_Client_ID"))
m_AD_Client_ID = ((BigDecimal)para[i].getParameter()).intValue(); m_AD_Client_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("DeleteOldImported")) else if (name.equals("DeleteOldImported"))
m_deleteOldImported = "Y".equals(para[i].getParameter()); m_deleteOldImported = "Y".equals(para[i].getParameter());
else else
log.log(Level.SEVERE, "Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
if (m_DateValue == null) if (m_DateValue == null)
m_DateValue = new Timestamp (System.currentTimeMillis()); m_DateValue = new Timestamp (System.currentTimeMillis());
} // prepare } // prepare
/** /**
* Perrform process. * Perrform process.
* @return Message * @return Message
* @throws Exception * @throws Exception
*/ */
protected String doIt() throws java.lang.Exception protected String doIt() throws java.lang.Exception
{ {
StringBuffer sql = null; StringBuffer sql = null;
int no = 0; int no = 0;
String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID;
// **** Prepare **** // **** Prepare ****
// Delete Old Imported // Delete Old Imported
if (m_deleteOldImported) if (m_deleteOldImported)
{ {
sql = new StringBuffer ("DELETE I_BPartner " sql = new StringBuffer ("DELETE I_BPartner "
+ "WHERE I_IsImported='Y'").append(clientCheck); + "WHERE I_IsImported='Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Delete Old Impored =" + no); log.fine("Delete Old Impored =" + no);
} }
// Set Client, Org, IsActive, Created/Updated // Set Client, Org, IsActive, Created/Updated
sql = new StringBuffer ("UPDATE I_BPartner " sql = new StringBuffer ("UPDATE I_BPartner "
+ "SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append(")," + "SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append("),"
+ " AD_Org_ID = COALESCE (AD_Org_ID, 0)," + " AD_Org_ID = COALESCE (AD_Org_ID, 0),"
+ " IsActive = COALESCE (IsActive, 'Y')," + " IsActive = COALESCE (IsActive, 'Y'),"
+ " Created = COALESCE (Created, SysDate)," + " Created = COALESCE (Created, SysDate),"
+ " CreatedBy = COALESCE (CreatedBy, 0)," + " CreatedBy = COALESCE (CreatedBy, 0),"
+ " Updated = COALESCE (Updated, SysDate)," + " Updated = COALESCE (Updated, SysDate),"
+ " UpdatedBy = COALESCE (UpdatedBy, 0)," + " UpdatedBy = COALESCE (UpdatedBy, 0),"
+ " I_ErrorMsg = NULL," + " I_ErrorMsg = NULL,"
+ " I_IsImported = 'N' " + " I_IsImported = 'N' "
+ "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL"); + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Reset=" + no); log.fine("Reset=" + no);
// Set BP_Group // Set BP_Group
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET GroupValue=(SELECT Value FROM C_BP_Group g WHERE g.IsDefault='Y'" + "SET GroupValue=(SELECT Value FROM C_BP_Group g WHERE g.IsDefault='Y'"
+ " AND g.AD_Client_ID=i.AD_Client_ID AND ROWNUM=1) " + " AND g.AD_Client_ID=i.AD_Client_ID AND ROWNUM=1) "
+ "WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL" + "WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Group Default=" + no); log.fine("Set Group Default=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g" + "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 i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) "
+ "WHERE C_BP_Group_ID IS NULL" + "WHERE C_BP_Group_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Group=" + no); log.fine("Set Group=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner " sql = new StringBuffer ("UPDATE I_BPartner "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' "
+ "WHERE C_BP_Group_ID IS NULL" + "WHERE C_BP_Group_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.config("Invalid Group=" + no); log.config("Invalid Group=" + no);
// Set Country // Set Country
/** /**
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET CountryCode=(SELECT CountryCode FROM C_Country c WHERE c.IsDefault='Y'" + "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) " + " AND c.AD_Client_ID IN (0, i.AD_Client_ID) AND ROWNUM=1) "
+ "WHERE CountryCode IS NULL AND C_Country_ID IS NULL" + "WHERE CountryCode IS NULL AND C_Country_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Country Default=" + no); log.fine("Set Country Default=" + no);
**/ **/
// //
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c" + "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c"
+ " WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) " + " WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) "
+ "WHERE C_Country_ID IS NULL" + "WHERE C_Country_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Country=" + no); log.fine("Set Country=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner " sql = new StringBuffer ("UPDATE I_BPartner "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' "
+ "WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)" + "WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.config("Invalid Country=" + no); log.config("Invalid Country=" + no);
// Set Region // Set Region
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "Set RegionName=(SELECT Name FROM C_Region r" + "Set RegionName=(SELECT Name FROM C_Region r"
+ " WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID" + " WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID"
+ " AND r.AD_Client_ID IN (0, i.AD_Client_ID) AND ROWNUM=1) " + " AND r.AD_Client_ID IN (0, i.AD_Client_ID) AND ROWNUM=1) "
+ "WHERE RegionName IS NULL AND C_Region_ID IS NULL" + "WHERE RegionName IS NULL AND C_Region_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Region Default=" + no); log.fine("Set Region Default=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r" + "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" + " 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)) " + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) "
+ "WHERE C_Region_ID IS NULL" + "WHERE C_Region_ID IS NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Region=" + no); log.fine("Set Region=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' "
+ "WHERE C_Region_ID IS NULL " + "WHERE C_Region_ID IS NULL "
+ " AND EXISTS (SELECT * FROM C_Country c" + " AND EXISTS (SELECT * FROM C_Country c"
+ " WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')" + " WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.config("Invalid Region=" + no); log.config("Invalid Region=" + no);
// Set Greeting // Set Greeting
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g" + "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 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" + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Greeting=" + no); log.fine("Set Greeting=" + no);
// //
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' "
+ "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL" + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL"
+ " AND I_IsImported<>'Y'").append(clientCheck); + " AND I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.config("Invalid Greeting=" + no); log.config("Invalid Greeting=" + no);
// Existing User ? // Existing User ?
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET (C_BPartner_ID,AD_User_ID)=" + "SET (C_BPartner_ID,AD_User_ID)="
+ "(SELECT C_BPartner_ID,AD_User_ID FROM AD_User u " + "(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=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) "
+ "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck); + "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Found EMail User=" + no); log.fine("Found EMail User=" + no);
// Existing BPartner ? Match Value // Existing BPartner ? Match Value
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p" + "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 i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) "
+ "WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL" + "WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL"
+ " AND I_IsImported='N'").append(clientCheck); + " AND I_IsImported='N'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Found BPartner=" + no); log.fine("Found BPartner=" + no);
// Existing Contact ? Match Name // Existing Contact ? Match Name
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c" + "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 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" + "WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL"
+ " AND I_IsImported='N'").append(clientCheck); + " AND I_IsImported='N'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Found Contact=" + no); log.fine("Found Contact=" + no);
// Existing Location ? Exact Match // Existing Location ? Exact Match
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID" + "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)" + " 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" + " 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.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.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)) " + " 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" + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL"
+ " AND I_IsImported='N'").append(clientCheck); + " AND I_IsImported='N'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Found Location=" + no); log.fine("Found Location=" + no);
// Interest Area // Interest Area
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia " + "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 i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) "
+ "WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL" + "WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL"
+ " AND I_IsImported='N'").append(clientCheck); + " AND I_IsImported='N'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
log.fine("Set Interest Area=" + no); log.fine("Set Interest Area=" + no);
commit(); commit();
// ------------------------------------------------------------------- // -------------------------------------------------------------------
int noInsert = 0; int noInsert = 0;
int noUpdate = 0; int noUpdate = 0;
// Go through Records // Go through Records
sql = new StringBuffer ("SELECT * FROM I_BPartner " sql = new StringBuffer ("SELECT * FROM I_BPartner "
+ "WHERE I_IsImported='N'").append(clientCheck); + "WHERE I_IsImported='N'").append(clientCheck);
try try
{ {
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); PreparedStatement pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) while (rs.next())
{ {
X_I_BPartner impBP = new X_I_BPartner (getCtx(), rs, get_TrxName()); X_I_BPartner impBP = new X_I_BPartner (getCtx(), rs, get_TrxName());
log.fine("I_BPartner_ID=" + impBP.getI_BPartner_ID() log.fine("I_BPartner_ID=" + impBP.getI_BPartner_ID()
+ ", C_BPartner_ID=" + impBP.getC_BPartner_ID() + ", C_BPartner_ID=" + impBP.getC_BPartner_ID()
+ ", C_BPartner_Location_ID=" + impBP.getC_BPartner_Location_ID() + ", C_BPartner_Location_ID=" + impBP.getC_BPartner_Location_ID()
+ ", AD_User_ID=" + impBP.getAD_User_ID()); + ", AD_User_ID=" + impBP.getAD_User_ID());
// **** Create/Update BPartner **** // **** Create/Update BPartner ****
MBPartner bp = null; MBPartner bp = null;
if (impBP.getC_BPartner_ID() == 0) // Insert new BPartner if (impBP.getC_BPartner_ID() == 0) // Insert new BPartner
{ {
bp = new MBPartner(impBP); bp = new MBPartner(impBP);
if (bp.save()) if (bp.save())
{ {
impBP.setC_BPartner_ID(bp.getC_BPartner_ID()); impBP.setC_BPartner_ID(bp.getC_BPartner_ID());
log.finest("Insert BPartner - " + bp.getC_BPartner_ID()); log.finest("Insert BPartner - " + bp.getC_BPartner_ID());
noInsert++; noInsert++;
} }
else else
{ {
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Insert BPartner, ' ") .append("Cannot Insert BPartner")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
} }
else // Update existing BPartner else // Update existing BPartner
{ {
bp = new MBPartner(getCtx(), impBP.getC_BPartner_ID(), get_TrxName()); bp = new MBPartner(getCtx(), impBP.getC_BPartner_ID(), get_TrxName());
// if (impBP.getValue() != null) // not to overwite // if (impBP.getValue() != null) // not to overwite
// bp.setValue(impBP.getValue()); // bp.setValue(impBP.getValue());
if (impBP.getName() != null) if (impBP.getName() != null)
{ {
bp.setName(impBP.getName()); bp.setName(impBP.getName());
bp.setName2(impBP.getName2()); bp.setName2(impBP.getName2());
} }
if (impBP.getDUNS() != null) if (impBP.getDUNS() != null)
bp.setDUNS(impBP.getDUNS()); bp.setDUNS(impBP.getDUNS());
if (impBP.getTaxID() != null) if (impBP.getTaxID() != null)
bp.setTaxID(impBP.getTaxID()); bp.setTaxID(impBP.getTaxID());
if (impBP.getNAICS() != null) if (impBP.getNAICS() != null)
bp.setNAICS(impBP.getNAICS()); bp.setNAICS(impBP.getNAICS());
if (impBP.getC_BP_Group_ID() != 0) if (impBP.getC_BP_Group_ID() != 0)
bp.setC_BP_Group_ID(impBP.getC_BP_Group_ID()); bp.setC_BP_Group_ID(impBP.getC_BP_Group_ID());
// //
if (bp.save()) if (bp.save())
{ {
log.finest("Update BPartner - " + bp.getC_BPartner_ID()); log.finest("Update BPartner - " + bp.getC_BPartner_ID());
noUpdate++; noUpdate++;
} }
else else
{ {
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Update BPartner, ' ") .append("Cannot Update BPartner")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
} }
// **** Create/Update BPartner Location **** // **** Create/Update BPartner Location ****
MBPartnerLocation bpl = null; MBPartnerLocation bpl = null;
if (impBP.getC_BPartner_Location_ID() != 0) // Update Location if (impBP.getC_BPartner_Location_ID() != 0) // Update Location
{ {
bpl = new MBPartnerLocation(getCtx(), impBP.getC_BPartner_Location_ID(), get_TrxName()); bpl = new MBPartnerLocation(getCtx(), impBP.getC_BPartner_Location_ID(), get_TrxName());
MLocation location = new MLocation(getCtx(), bpl.getC_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_Country_ID(impBP.getC_Country_ID());
location.setC_Region_ID(impBP.getC_Region_ID()); location.setC_Region_ID(impBP.getC_Region_ID());
location.setCity(impBP.getCity()); location.setCity(impBP.getCity());
location.setAddress1(impBP.getAddress1()); location.setAddress1(impBP.getAddress1());
location.setAddress2(impBP.getAddress2()); location.setAddress2(impBP.getAddress2());
location.setPostal(impBP.getPostal()); location.setPostal(impBP.getPostal());
location.setPostal_Add(impBP.getPostal_Add()); location.setPostal_Add(impBP.getPostal_Add());
if (!location.save()) if (!location.save())
log.warning("Location not updated"); log.warning("Location not updated");
else else
bpl.setC_Location_ID(location.getC_Location_ID()); bpl.setC_Location_ID(location.getC_Location_ID());
if (impBP.getPhone() != null) if (impBP.getPhone() != null)
bpl.setPhone(impBP.getPhone()); bpl.setPhone(impBP.getPhone());
if (impBP.getPhone2() != null) if (impBP.getPhone2() != null)
bpl.setPhone2(impBP.getPhone2()); bpl.setPhone2(impBP.getPhone2());
if (impBP.getFax() != null) if (impBP.getFax() != null)
bpl.setFax(impBP.getFax()); bpl.setFax(impBP.getFax());
bpl.save(); bpl.save();
} }
else // New Location else // New Location
if (impBP.getC_Country_ID() != 0 if (impBP.getC_Country_ID() != 0
&& impBP.getAddress1() != null && impBP.getAddress1() != null
&& impBP.getCity() != null) && impBP.getCity() != null)
{ {
MLocation location = new MLocation(getCtx(), impBP.getC_Country_ID(), MLocation location = new MLocation(getCtx(), impBP.getC_Country_ID(),
impBP.getC_Region_ID(), impBP.getCity(), get_TrxName()); impBP.getC_Region_ID(), impBP.getCity(), get_TrxName());
location.setAddress1(impBP.getAddress1()); location.setAddress1(impBP.getAddress1());
location.setAddress2(impBP.getAddress2()); location.setAddress2(impBP.getAddress2());
location.setPostal(impBP.getPostal()); location.setPostal(impBP.getPostal());
location.setPostal_Add(impBP.getPostal_Add()); location.setPostal_Add(impBP.getPostal_Add());
if (location.save()) if (location.save())
log.finest("Insert Location - " + location.getC_Location_ID()); log.finest("Insert Location - " + location.getC_Location_ID());
else else
{ {
rollback(); rollback();
noInsert--; noInsert--;
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Insert Location, ' ") .append("Cannot Insert Location")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
// //
bpl = new MBPartnerLocation (bp); bpl = new MBPartnerLocation (bp);
bpl.setC_Location_ID(location.getC_Location_ID()); bpl.setC_Location_ID(location.getC_Location_ID());
bpl.setPhone(impBP.getPhone()); bpl.setPhone(impBP.getPhone());
bpl.setPhone2(impBP.getPhone2()); bpl.setPhone2(impBP.getPhone2());
bpl.setFax(impBP.getFax()); bpl.setFax(impBP.getFax());
if (bpl.save()) if (bpl.save())
{ {
log.finest("Insert BP Location - " + bpl.getC_BPartner_Location_ID()); log.finest("Insert BP Location - " + bpl.getC_BPartner_Location_ID());
impBP.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); impBP.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
} }
else else
{ {
rollback(); rollback();
noInsert--; noInsert--;
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Insert BPLocation, ' ") .append("Cannot Insert BPLocation")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
} }
// **** Create/Update Contact **** // **** Create/Update Contact ****
MUser user = null; MUser user = null;
if (impBP.getAD_User_ID() != 0) if (impBP.getAD_User_ID() != 0)
{ {
user = new MUser (getCtx(), impBP.getAD_User_ID(), get_TrxName()); user = new MUser (getCtx(), impBP.getAD_User_ID(), get_TrxName());
if (user.getC_BPartner_ID() == 0) if (user.getC_BPartner_ID() == 0)
user.setC_BPartner_ID(bp.getC_BPartner_ID()); user.setC_BPartner_ID(bp.getC_BPartner_ID());
else if (user.getC_BPartner_ID() != bp.getC_BPartner_ID()) else if (user.getC_BPartner_ID() != bp.getC_BPartner_ID())
{ {
rollback(); rollback();
noInsert--; noInsert--;
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'BP of User <> BP, ' ") .append("BP of User <> BP")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
if (impBP.getC_Greeting_ID() != 0) if (impBP.getC_Greeting_ID() != 0)
user.setC_Greeting_ID(impBP.getC_Greeting_ID()); user.setC_Greeting_ID(impBP.getC_Greeting_ID());
String name = impBP.getContactName(); String name = impBP.getContactName();
if (name == null || name.length() == 0) if (name == null || name.length() == 0)
name = impBP.getEMail(); name = impBP.getEMail();
user.setName(name); user.setName(name);
if (impBP.getTitle() != null) if (impBP.getTitle() != null)
user.setTitle(impBP.getTitle()); user.setTitle(impBP.getTitle());
if (impBP.getContactDescription() != null) if (impBP.getContactDescription() != null)
user.setDescription(impBP.getContactDescription()); user.setDescription(impBP.getContactDescription());
if (impBP.getComments() != null) if (impBP.getComments() != null)
user.setComments(impBP.getComments()); user.setComments(impBP.getComments());
if (impBP.getPhone() != null) if (impBP.getPhone() != null)
user.setPhone(impBP.getPhone()); user.setPhone(impBP.getPhone());
if (impBP.getPhone2() != null) if (impBP.getPhone2() != null)
user.setPhone(impBP.getPhone2()); user.setPhone(impBP.getPhone2());
if (impBP.getFax() != null) if (impBP.getFax() != null)
user.setFax(impBP.getFax()); user.setFax(impBP.getFax());
if (impBP.getEMail() != null) if (impBP.getEMail() != null)
user.setEMail(impBP.getEMail()); user.setEMail(impBP.getEMail());
if (impBP.getBirthday() != null) if (impBP.getBirthday() != null)
user.setBirthday(impBP.getBirthday()); user.setBirthday(impBP.getBirthday());
if (bpl != null) if (bpl != null)
user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
if (user.save()) if (user.save())
{ {
log.finest("Update BP Contact - " + user.getAD_User_ID()); log.finest("Update BP Contact - " + user.getAD_User_ID());
} }
else else
{ {
rollback(); rollback();
noInsert--; noInsert--;
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Update BP Contact, ' ") .append("Cannot Update BP Contact")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
} }
else // New Contact else // New Contact
if (impBP.getContactName() != null || impBP.getEMail() != null) if (impBP.getContactName() != null || impBP.getEMail() != null)
{ {
user = new MUser (bp); user = new MUser (bp);
if (impBP.getC_Greeting_ID() != 0) if (impBP.getC_Greeting_ID() != 0)
user.setC_Greeting_ID(impBP.getC_Greeting_ID()); user.setC_Greeting_ID(impBP.getC_Greeting_ID());
String name = impBP.getContactName(); String name = impBP.getContactName();
if (name == null || name.length() == 0) if (name == null || name.length() == 0)
name = impBP.getEMail(); name = impBP.getEMail();
user.setName(name); user.setName(name);
user.setTitle(impBP.getTitle()); user.setTitle(impBP.getTitle());
user.setDescription(impBP.getContactDescription()); user.setDescription(impBP.getContactDescription());
user.setComments(impBP.getComments()); user.setComments(impBP.getComments());
user.setPhone(impBP.getPhone()); user.setPhone(impBP.getPhone());
user.setPhone(impBP.getPhone2()); user.setPhone(impBP.getPhone2());
user.setFax(impBP.getFax()); user.setFax(impBP.getFax());
user.setEMail(impBP.getEMail()); user.setEMail(impBP.getEMail());
user.setBirthday(impBP.getBirthday()); user.setBirthday(impBP.getBirthday());
if (bpl != null) if (bpl != null)
user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID()); user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
if (user.save()) if (user.save())
{ {
log.finest("Insert BP Contact - " + user.getAD_User_ID()); log.finest("Insert BP Contact - " + user.getAD_User_ID());
impBP.setAD_User_ID(user.getAD_User_ID()); impBP.setAD_User_ID(user.getAD_User_ID());
} }
else else
{ {
rollback(); rollback();
noInsert--; noInsert--;
sql = new StringBuffer ("UPDATE I_BPartner i " sql = new StringBuffer ("UPDATE I_BPartner i "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||") + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||")
.append("'Cannot Insert BPContact, ' ") .append("Cannot Insert BPContact")
.append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID()); .append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
DB.executeUpdate(sql.toString(), get_TrxName()); DB.executeUpdate(sql.toString(), get_TrxName());
continue; continue;
} }
} }
// Interest Area // Interest Area
if (impBP.getR_InterestArea_ID() != 0 && user != null) if (impBP.getR_InterestArea_ID() != 0 && user != null)
{ {
MContactInterest ci = MContactInterest.get(getCtx(), MContactInterest ci = MContactInterest.get(getCtx(),
impBP.getR_InterestArea_ID(), user.getAD_User_ID(), impBP.getR_InterestArea_ID(), user.getAD_User_ID(),
true, get_TrxName()); true, get_TrxName());
ci.save(); // don't subscribe or re-activate ci.save(); // don't subscribe or re-activate
} }
// //
impBP.setI_IsImported(true); impBP.setI_IsImported(true);
impBP.setProcessed(true); impBP.setProcessed(true);
impBP.setProcessing(false); impBP.setProcessing(false);
impBP.save(); impBP.save();
commit(); commit();
} // for all I_Product } // for all I_Product
rs.close(); rs.close();
pstmt.close(); pstmt.close();
} }
catch (SQLException e) catch (SQLException e)
{ {
log.log(Level.SEVERE, "", e); log.log(Level.SEVERE, "", e);
rollback(); rollback();
} }
// Set Error to indicator to not imported // Set Error to indicator to not imported
sql = new StringBuffer ("UPDATE I_BPartner " sql = new StringBuffer ("UPDATE I_BPartner "
+ "SET I_IsImported='N', Updated=SysDate " + "SET I_IsImported='N', Updated=SysDate "
+ "WHERE I_IsImported<>'Y'").append(clientCheck); + "WHERE I_IsImported<>'Y'").append(clientCheck);
no = DB.executeUpdate(sql.toString(), get_TrxName()); no = DB.executeUpdate(sql.toString(), get_TrxName());
addLog (0, null, new BigDecimal (no), "@Errors@"); addLog (0, null, new BigDecimal (no), "@Errors@");
addLog (0, null, new BigDecimal (noInsert), "@C_BPartner_ID@: @Inserted@"); addLog (0, null, new BigDecimal (noInsert), "@C_BPartner_ID@: @Inserted@");
addLog (0, null, new BigDecimal (noUpdate), "@C_BPartner_ID@: @Updated@"); addLog (0, null, new BigDecimal (noUpdate), "@C_BPartner_ID@: @Updated@");
return ""; return "";
} // doIt } // doIt
} // ImportBPartner } // ImportBPartner

View File

@ -3,366 +3,366 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.process; package org.compiere.process;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import java.math.*; import java.math.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Invoice Not realized Gain & Loss. * Invoice Not realized Gain & Loss.
* The actual data shown is T_InvoiceGL_v * The actual data shown is T_InvoiceGL_v
* @author Jorg Janke * @author Jorg Janke
* @version $Id: InvoiceNGL.java,v 1.3 2006/08/04 03:53:59 jjanke Exp $ * @version $Id: InvoiceNGL.java,v 1.3 2006/08/04 03:53:59 jjanke Exp $
*/ */
public class InvoiceNGL extends SvrProcess public class InvoiceNGL extends SvrProcess
{ {
/** Mandatory Acct Schema */ /** Mandatory Acct Schema */
private int p_C_AcctSchema_ID = 0; private int p_C_AcctSchema_ID = 0;
/** Mandatory Conversion Type */ /** Mandatory Conversion Type */
private int p_C_ConversionTypeReval_ID = 0; private int p_C_ConversionTypeReval_ID = 0;
/** Revaluation Date */ /** Revaluation Date */
private Timestamp p_DateReval = null; private Timestamp p_DateReval = null;
/** Only AP/AR Transactions */ /** Only AP/AR Transactions */
private String p_APAR = "A"; private String p_APAR = "A";
private static String ONLY_AP = "P"; private static String ONLY_AP = "P";
private static String ONLY_AR = "R"; private static String ONLY_AR = "R";
/** Report all Currencies */ /** Report all Currencies */
private boolean p_IsAllCurrencies = false; private boolean p_IsAllCurrencies = false;
/** Optional Invoice Currency */ /** Optional Invoice Currency */
private int p_C_Currency_ID = 0; private int p_C_Currency_ID = 0;
/** GL Document Type */ /** GL Document Type */
private int p_C_DocTypeReval_ID = 0; private int p_C_DocTypeReval_ID = 0;
/** /**
* Prepare - e.g., get Parameters. * Prepare - e.g., get Parameters.
*/ */
protected void prepare() protected void prepare()
{ {
ProcessInfoParameter[] para = getParameter(); ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++) for (int i = 0; i < para.length; i++)
{ {
String name = para[i].getParameterName(); String name = para[i].getParameterName();
if (para[i].getParameter() == null) if (para[i].getParameter() == null)
; ;
else if (name.equals("C_AcctSchema_ID")) else if (name.equals("C_AcctSchema_ID"))
p_C_AcctSchema_ID = para[i].getParameterAsInt(); p_C_AcctSchema_ID = para[i].getParameterAsInt();
else if (name.equals("C_ConversionTypeReval_ID")) else if (name.equals("C_ConversionTypeReval_ID"))
p_C_ConversionTypeReval_ID = para[i].getParameterAsInt(); p_C_ConversionTypeReval_ID = para[i].getParameterAsInt();
else if (name.equals("DateReval")) else if (name.equals("DateReval"))
p_DateReval = (Timestamp)para[i].getParameter(); p_DateReval = (Timestamp)para[i].getParameter();
else if (name.equals("APAR")) else if (name.equals("APAR"))
p_APAR = (String)para[i].getParameter(); p_APAR = (String)para[i].getParameter();
else if (name.equals("IsAllCurrencies")) else if (name.equals("IsAllCurrencies"))
p_IsAllCurrencies = "Y".equals((String)para[i].getParameter()); p_IsAllCurrencies = "Y".equals((String)para[i].getParameter());
else if (name.equals("C_Currency_ID")) else if (name.equals("C_Currency_ID"))
p_C_Currency_ID = para[i].getParameterAsInt(); p_C_Currency_ID = para[i].getParameterAsInt();
else if (name.equals("C_DocTypeReval_ID")) else if (name.equals("C_DocTypeReval_ID"))
p_C_DocTypeReval_ID = para[i].getParameterAsInt(); p_C_DocTypeReval_ID = para[i].getParameterAsInt();
else else
log.log(Level.SEVERE, "Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
} // prepare } // prepare
/** /**
* Process * Process
* @return info * @return info
* @throws Exception * @throws Exception
*/ */
protected String doIt () throws Exception protected String doIt () throws Exception
{ {
if (p_IsAllCurrencies) if (p_IsAllCurrencies)
p_C_Currency_ID = 0; p_C_Currency_ID = 0;
log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID
+ ",C_ConversionTypeReval_ID=" + p_C_ConversionTypeReval_ID + ",C_ConversionTypeReval_ID=" + p_C_ConversionTypeReval_ID
+ ",DateReval=" + p_DateReval + ",DateReval=" + p_DateReval
+ ", APAR=" + p_APAR + ", APAR=" + p_APAR
+ ", IsAllCurrencies=" + p_IsAllCurrencies + ", IsAllCurrencies=" + p_IsAllCurrencies
+ ",C_Currency_ID=" + p_C_Currency_ID + ",C_Currency_ID=" + p_C_Currency_ID
+ ", C_DocType_ID=" + p_C_DocTypeReval_ID); + ", C_DocType_ID=" + p_C_DocTypeReval_ID);
// Parameter // Parameter
if (p_DateReval == null) if (p_DateReval == null)
p_DateReval = new Timestamp(System.currentTimeMillis()); p_DateReval = new Timestamp(System.currentTimeMillis());
// Delete - just to be sure // Delete - just to be sure
String sql = "DELETE T_InvoiceGL WHERE AD_PInstance_ID=" + getAD_PInstance_ID(); String sql = "DELETE T_InvoiceGL WHERE AD_PInstance_ID=" + getAD_PInstance_ID();
int no = DB.executeUpdate(sql, get_TrxName()); int no = DB.executeUpdate(sql, get_TrxName());
if (no > 0) if (no > 0)
log.info("Deleted #" + no); log.info("Deleted #" + no);
// Insert Trx // Insert Trx
String dateStr = DB.TO_DATE(p_DateReval, true); String dateStr = DB.TO_DATE(p_DateReval, true);
sql = "INSERT INTO T_InvoiceGL (AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy, Updated,UpdatedBy," sql = "INSERT INTO T_InvoiceGL (AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy, Updated,UpdatedBy,"
+ " AD_PInstance_ID, C_Invoice_ID, GrandTotal, OpenAmt, " + " AD_PInstance_ID, C_Invoice_ID, GrandTotal, OpenAmt, "
+ " Fact_Acct_ID, AmtSourceBalance, AmtAcctBalance, " + " Fact_Acct_ID, AmtSourceBalance, AmtAcctBalance, "
+ " AmtRevalDr, AmtRevalCr, C_DocTypeReval_ID, IsAllCurrencies, " + " AmtRevalDr, AmtRevalCr, C_DocTypeReval_ID, IsAllCurrencies, "
+ " DateReval, C_ConversionTypeReval_ID, AmtRevalDrDiff, AmtRevalCrDiff, APAR) " + " DateReval, C_ConversionTypeReval_ID, AmtRevalDrDiff, AmtRevalCrDiff, APAR) "
// -- // --
+ "SELECT i.AD_Client_ID, i.AD_Org_ID, i.IsActive, i.Created,i.CreatedBy, i.Updated,i.UpdatedBy," + "SELECT i.AD_Client_ID, i.AD_Org_ID, i.IsActive, i.Created,i.CreatedBy, i.Updated,i.UpdatedBy,"
+ getAD_PInstance_ID() + ", i.C_Invoice_ID, i.GrandTotal, invoiceOpen(i.C_Invoice_ID, 0), " + getAD_PInstance_ID() + ", i.C_Invoice_ID, i.GrandTotal, invoiceOpen(i.C_Invoice_ID, 0), "
+ " fa.Fact_Acct_ID, fa.AmtSourceDr-fa.AmtSourceCr, fa.AmtAcctDr-fa.AmtAcctCr, " + " fa.Fact_Acct_ID, fa.AmtSourceDr-fa.AmtSourceCr, fa.AmtAcctDr-fa.AmtAcctCr, "
// AmtRevalDr, AmtRevalCr, // AmtRevalDr, AmtRevalCr,
+ " currencyConvert(fa.AmtSourceDr, i.C_Currency_ID, a.C_Currency_ID, " + dateStr + ", " + p_C_ConversionTypeReval_ID + ", i.AD_Client_ID, i.AD_Org_ID)," + " currencyConvert(fa.AmtSourceDr, i.C_Currency_ID, a.C_Currency_ID, " + dateStr + ", " + p_C_ConversionTypeReval_ID + ", i.AD_Client_ID, i.AD_Org_ID),"
+ " currencyConvert(fa.AmtSourceCr, i.C_Currency_ID, a.C_Currency_ID, " + dateStr + ", " + p_C_ConversionTypeReval_ID + ", i.AD_Client_ID, i.AD_Org_ID)," + " currencyConvert(fa.AmtSourceCr, i.C_Currency_ID, a.C_Currency_ID, " + dateStr + ", " + p_C_ConversionTypeReval_ID + ", i.AD_Client_ID, i.AD_Org_ID),"
+ (p_C_DocTypeReval_ID==0 ? "NULL" : String.valueOf(p_C_DocTypeReval_ID)) + ", " + (p_C_DocTypeReval_ID==0 ? "NULL" : String.valueOf(p_C_DocTypeReval_ID)) + ", "
+ (p_IsAllCurrencies ? "'Y'," : "'N',") + (p_IsAllCurrencies ? "'Y'," : "'N',")
+ dateStr + ", " + p_C_ConversionTypeReval_ID + ", 0, 0, '" + p_APAR + "' " + dateStr + ", " + p_C_ConversionTypeReval_ID + ", 0, 0, '" + p_APAR + "' "
// //
+ "FROM C_Invoice_v i" + "FROM C_Invoice_v i"
+ " INNER JOIN Fact_Acct fa ON (fa.AD_Table_ID=318 AND fa.Record_ID=i.C_Invoice_ID" + " INNER JOIN Fact_Acct fa ON (fa.AD_Table_ID=318 AND fa.Record_ID=i.C_Invoice_ID"
+ " AND (i.GrandTotal=fa.AmtSourceDr OR i.GrandTotal=fa.AmtSourceCr))" + " AND (i.GrandTotal=fa.AmtSourceDr OR i.GrandTotal=fa.AmtSourceCr))"
+ " INNER JOIN C_AcctSchema a ON (fa.C_AcctSchema_ID=a.C_AcctSchema_ID) " + " INNER JOIN C_AcctSchema a ON (fa.C_AcctSchema_ID=a.C_AcctSchema_ID) "
+ "WHERE i.IsPaid='N'" + "WHERE i.IsPaid='N'"
+ " AND EXISTS (SELECT * FROM C_ElementValue ev " + " AND EXISTS (SELECT * FROM C_ElementValue ev "
+ "WHERE ev.C_ElementValue_ID=fa.Account_ID AND (ev.AccountType='A' OR ev.AccountType='L'))" + "WHERE ev.C_ElementValue_ID=fa.Account_ID AND (ev.AccountType='A' OR ev.AccountType='L'))"
+ " AND fa.C_AcctSchema_ID=" + p_C_AcctSchema_ID; + " AND fa.C_AcctSchema_ID=" + p_C_AcctSchema_ID;
if (!p_IsAllCurrencies) if (!p_IsAllCurrencies)
sql += " AND i.C_Currency_ID<>a.C_Currency_ID"; sql += " AND i.C_Currency_ID<>a.C_Currency_ID";
if (ONLY_AR.equals(p_APAR)) if (ONLY_AR.equals(p_APAR))
sql += " AND i.IsSOTrx='Y'"; sql += " AND i.IsSOTrx='Y'";
else if (ONLY_AP.equals(p_APAR)) else if (ONLY_AP.equals(p_APAR))
sql += " AND i.IsSOTrx='N'"; sql += " AND i.IsSOTrx='N'";
if (!p_IsAllCurrencies && p_C_Currency_ID != 0) if (!p_IsAllCurrencies && p_C_Currency_ID != 0)
sql += " AND i.C_Currency_ID=" + p_C_Currency_ID; sql += " AND i.C_Currency_ID=" + p_C_Currency_ID;
no = DB.executeUpdate(sql, get_TrxName()); no = DB.executeUpdate(sql, get_TrxName());
if (no != 0) if (no != 0)
log.info("Inserted #" + no); log.info("Inserted #" + no);
else if (CLogMgt.isLevelFiner()) else if (CLogMgt.isLevelFiner())
log.warning("Inserted #" + no + " - " + sql); log.warning("Inserted #" + no + " - " + sql);
else else
log.warning("Inserted #" + no); log.warning("Inserted #" + no);
// Calculate Difference // Calculate Difference
sql = "UPDATE T_InvoiceGL gl " sql = "UPDATE T_InvoiceGL gl "
+ "SET (AmtRevalDrDiff,AmtRevalCrDiff)=" + "SET (AmtRevalDrDiff,AmtRevalCrDiff)="
+ "(SELECT gl.AmtRevalDr-fa.AmtAcctDr, gl.AmtRevalCr-fa.AmtAcctCr " + "(SELECT gl.AmtRevalDr-fa.AmtAcctDr, gl.AmtRevalCr-fa.AmtAcctCr "
+ "FROM Fact_Acct fa " + "FROM Fact_Acct fa "
+ "WHERE gl.Fact_Acct_ID=fa.Fact_Acct_ID) " + "WHERE gl.Fact_Acct_ID=fa.Fact_Acct_ID) "
+ "WHERE AD_PInstance_ID=" + getAD_PInstance_ID(); + "WHERE AD_PInstance_ID=" + getAD_PInstance_ID();
int noT = DB.executeUpdate(sql, get_TrxName()); int noT = DB.executeUpdate(sql, get_TrxName());
if (noT > 0) if (noT > 0)
log.config("Difference #" + noT); log.config("Difference #" + noT);
// Percentage // Percentage
sql = "UPDATE T_InvoiceGL SET Percent = 100 " sql = "UPDATE T_InvoiceGL SET Percent = 100 "
+ "WHERE GrandTotal=OpenAmt AND AD_PInstance_ID=" + getAD_PInstance_ID(); + "WHERE GrandTotal=OpenAmt AND AD_PInstance_ID=" + getAD_PInstance_ID();
no = DB.executeUpdate(sql, get_TrxName()); no = DB.executeUpdate(sql, get_TrxName());
if (no > 0) if (no > 0)
log.info("Not Paid #" + no); log.info("Not Paid #" + no);
sql = "UPDATE T_InvoiceGL SET Percent = ROUND(OpenAmt*100/GrandTotal,4) " sql = "UPDATE T_InvoiceGL SET Percent = ROUND(OpenAmt*100/GrandTotal,6) "
+ "WHERE GrandTotal<>OpenAmt AND GrandTotal <> 0 AND AD_PInstance_ID=" + getAD_PInstance_ID(); + "WHERE GrandTotal<>OpenAmt AND GrandTotal <> 0 AND AD_PInstance_ID=" + getAD_PInstance_ID();
no = DB.executeUpdate(sql, get_TrxName()); no = DB.executeUpdate(sql, get_TrxName());
if (no > 0) if (no > 0)
log.info("Partial Paid #" + no); log.info("Partial Paid #" + no);
sql = "UPDATE T_InvoiceGL SET AmtRevalDr = AmtRevalDr * Percent/100," sql = "UPDATE T_InvoiceGL SET AmtRevalDr = AmtRevalDr * Percent/100,"
+ " AmtRevalCr = AmtRevalCr * Percent/100," + " AmtRevalCr = AmtRevalCr * Percent/100,"
+ " AmtRevalDrDiff = AmtRevalDrDiff * Percent/100," + " AmtRevalDrDiff = AmtRevalDrDiff * Percent/100,"
+ " AmtRevalCrDiff = AmtRevalCrDiff * Percent/100 " + " AmtRevalCrDiff = AmtRevalCrDiff * Percent/100 "
+ "WHERE Percent <> 100 AND AD_PInstance_ID=" + getAD_PInstance_ID(); + "WHERE Percent <> 100 AND AD_PInstance_ID=" + getAD_PInstance_ID();
no = DB.executeUpdate(sql, get_TrxName()); no = DB.executeUpdate(sql, get_TrxName());
if (no > 0) if (no > 0)
log.config("Partial Calc #" + no); log.config("Partial Calc #" + no);
// Create Document // Create Document
String info = ""; String info = "";
if (p_C_DocTypeReval_ID != 0) if (p_C_DocTypeReval_ID != 0)
{ {
if (p_C_Currency_ID != 0) if (p_C_Currency_ID != 0)
log.warning("Can create Journal only for all currencies"); log.warning("Can create Journal only for all currencies");
else else
info = createGLJournal(); info = createGLJournal();
} }
return "#" + noT + info; return "#" + noT + info;
} // doIt } // doIt
/** /**
* Create GL Journal * Create GL Journal
* @return document info * @return document info
*/ */
private String createGLJournal() private String createGLJournal()
{ {
ArrayList<X_T_InvoiceGL> list = new ArrayList<X_T_InvoiceGL>(); ArrayList<X_T_InvoiceGL> list = new ArrayList<X_T_InvoiceGL>();
String sql = "SELECT * FROM T_InvoiceGL " String sql = "SELECT * FROM T_InvoiceGL "
+ "WHERE AD_PInstance_ID=" + getAD_PInstance_ID() + "WHERE AD_PInstance_ID=" + getAD_PInstance_ID()
+ " ORDER BY AD_Org_ID"; + " ORDER BY AD_Org_ID";
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt = DB.prepareStatement (sql, get_TrxName());
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
list.add (new X_T_InvoiceGL (getCtx(), rs, get_TrxName())); list.add (new X_T_InvoiceGL (getCtx(), rs, get_TrxName()));
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
log.log (Level.SEVERE, sql, e); log.log (Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
if (list.size() == 0) if (list.size() == 0)
return " - No Records found"; return " - No Records found";
// //
MAcctSchema as = MAcctSchema.get(getCtx(), p_C_AcctSchema_ID); MAcctSchema as = MAcctSchema.get(getCtx(), p_C_AcctSchema_ID);
MAcctSchemaDefault asDefaultAccts = MAcctSchemaDefault.get(getCtx(), p_C_AcctSchema_ID); MAcctSchemaDefault asDefaultAccts = MAcctSchemaDefault.get(getCtx(), p_C_AcctSchema_ID);
MGLCategory cat = MGLCategory.getDefaultSystem(getCtx()); MGLCategory cat = MGLCategory.getDefaultSystem(getCtx());
if (cat == null) if (cat == null)
{ {
MDocType docType = MDocType.get(getCtx(), p_C_DocTypeReval_ID); MDocType docType = MDocType.get(getCtx(), p_C_DocTypeReval_ID);
cat = MGLCategory.get(getCtx(), docType.getGL_Category_ID()); cat = MGLCategory.get(getCtx(), docType.getGL_Category_ID());
} }
// //
MJournalBatch batch = new MJournalBatch(getCtx(), 0, get_TrxName()); MJournalBatch batch = new MJournalBatch(getCtx(), 0, get_TrxName());
batch.setDescription (getName()); batch.setDescription (getName());
batch.setC_DocType_ID(p_C_DocTypeReval_ID); batch.setC_DocType_ID(p_C_DocTypeReval_ID);
batch.setDateDoc(new Timestamp(System.currentTimeMillis())); batch.setDateDoc(new Timestamp(System.currentTimeMillis()));
batch.setDateAcct(p_DateReval); batch.setDateAcct(p_DateReval);
batch.setC_Currency_ID(as.getC_Currency_ID()); batch.setC_Currency_ID(as.getC_Currency_ID());
if (!batch.save()) if (!batch.save())
return " - Could not create Batch"; return " - Could not create Batch";
// //
MJournal journal = null; MJournal journal = null;
BigDecimal drTotal = Env.ZERO; BigDecimal drTotal = Env.ZERO;
BigDecimal crTotal = Env.ZERO; BigDecimal crTotal = Env.ZERO;
int AD_Org_ID = 0; int AD_Org_ID = 0;
for (int i = 0; i < list.size(); i++) for (int i = 0; i < list.size(); i++)
{ {
X_T_InvoiceGL gl = list.get(i); X_T_InvoiceGL gl = list.get(i);
if (gl.getAmtRevalDrDiff().signum() == 0 && gl.getAmtRevalCrDiff().signum() == 0) if (gl.getAmtRevalDrDiff().signum() == 0 && gl.getAmtRevalCrDiff().signum() == 0)
continue; continue;
MInvoice invoice = new MInvoice(getCtx(), gl.getC_Invoice_ID(), null); MInvoice invoice = new MInvoice(getCtx(), gl.getC_Invoice_ID(), null);
if (invoice.getC_Currency_ID() == as.getC_Currency_ID()) if (invoice.getC_Currency_ID() == as.getC_Currency_ID())
continue; continue;
// //
if (journal == null) if (journal == null)
{ {
journal = new MJournal (batch); journal = new MJournal (batch);
journal.setC_AcctSchema_ID (as.getC_AcctSchema_ID()); journal.setC_AcctSchema_ID (as.getC_AcctSchema_ID());
journal.setC_Currency_ID(as.getC_Currency_ID()); journal.setC_Currency_ID(as.getC_Currency_ID());
journal.setC_ConversionType_ID(p_C_ConversionTypeReval_ID); journal.setC_ConversionType_ID(p_C_ConversionTypeReval_ID);
MOrg org = MOrg.get(getCtx(), gl.getAD_Org_ID()); MOrg org = MOrg.get(getCtx(), gl.getAD_Org_ID());
journal.setDescription (getName() + " - " + org.getName()); journal.setDescription (getName() + " - " + org.getName());
journal.setGL_Category_ID (cat.getGL_Category_ID()); journal.setGL_Category_ID (cat.getGL_Category_ID());
if (!journal.save()) if (!journal.save())
return " - Could not create Journal"; return " - Could not create Journal";
} }
// //
MJournalLine line = new MJournalLine(journal); MJournalLine line = new MJournalLine(journal);
line.setLine((i+1) * 10); line.setLine((i+1) * 10);
line.setDescription(invoice.getSummary()); line.setDescription(invoice.getSummary());
// //
MFactAcct fa = new MFactAcct (getCtx(), gl.getFact_Acct_ID(), null); MFactAcct fa = new MFactAcct (getCtx(), gl.getFact_Acct_ID(), null);
line.setC_ValidCombination_ID(MAccount.get(fa)); line.setC_ValidCombination_ID(MAccount.get(fa));
BigDecimal dr = gl.getAmtRevalDrDiff(); BigDecimal dr = gl.getAmtRevalDrDiff();
BigDecimal cr = gl.getAmtRevalCrDiff(); BigDecimal cr = gl.getAmtRevalCrDiff();
drTotal = drTotal.add(dr); drTotal = drTotal.add(dr);
crTotal = crTotal.add(cr); crTotal = crTotal.add(cr);
line.setAmtSourceDr (dr); line.setAmtSourceDr (dr);
line.setAmtAcctDr (dr); line.setAmtAcctDr (dr);
line.setAmtSourceCr (cr); line.setAmtSourceCr (cr);
line.setAmtAcctCr (cr); line.setAmtAcctCr (cr);
line.save(); line.save();
// //
if (AD_Org_ID == 0) // invoice org id if (AD_Org_ID == 0) // invoice org id
AD_Org_ID = gl.getAD_Org_ID(); AD_Org_ID = gl.getAD_Org_ID();
// Change in Org // Change in Org
if (AD_Org_ID != gl.getAD_Org_ID()) if (AD_Org_ID != gl.getAD_Org_ID())
{ {
createBalancing (asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (i+1) * 10); createBalancing (asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (i+1) * 10);
// //
AD_Org_ID = gl.getAD_Org_ID(); AD_Org_ID = gl.getAD_Org_ID();
drTotal = Env.ZERO; drTotal = Env.ZERO;
crTotal = Env.ZERO; crTotal = Env.ZERO;
journal = null; journal = null;
} }
} }
createBalancing (asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (list.size()+1) * 10); createBalancing (asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (list.size()+1) * 10);
return " - " + batch.getDocumentNo() + " #" + list.size(); return " - " + batch.getDocumentNo() + " #" + list.size();
} // createGLJournal } // createGLJournal
/** /**
* Create Balancing Entry * Create Balancing Entry
* @param asDefaultAccts acct schema default accounts * @param asDefaultAccts acct schema default accounts
* @param journal journal * @param journal journal
* @param drTotal dr * @param drTotal dr
* @param crTotal cr * @param crTotal cr
* @param AD_Org_ID org * @param AD_Org_ID org
* @param lineNo base line no * @param lineNo base line no
*/ */
private void createBalancing (MAcctSchemaDefault asDefaultAccts, MJournal journal, private void createBalancing (MAcctSchemaDefault asDefaultAccts, MJournal journal,
BigDecimal drTotal, BigDecimal crTotal, int AD_Org_ID, int lineNo) BigDecimal drTotal, BigDecimal crTotal, int AD_Org_ID, int lineNo)
{ {
if (journal == null) if (journal == null)
throw new IllegalArgumentException("Jornal is null"); throw new IllegalArgumentException("Jornal is null");
// CR Entry = Gain // CR Entry = Gain
if (drTotal.signum() != 0) if (drTotal.signum() != 0)
{ {
MJournalLine line = new MJournalLine(journal); MJournalLine line = new MJournalLine(journal);
line.setLine(lineNo+1); line.setLine(lineNo+1);
MAccount base = MAccount.get(getCtx(), asDefaultAccts.getUnrealizedGain_Acct()); MAccount base = MAccount.get(getCtx(), asDefaultAccts.getUnrealizedGain_Acct());
MAccount acct = MAccount.get(getCtx(), asDefaultAccts.getAD_Client_ID(), AD_Org_ID, MAccount acct = MAccount.get(getCtx(), asDefaultAccts.getAD_Client_ID(), AD_Org_ID,
asDefaultAccts.getC_AcctSchema_ID(), base.getAccount_ID(), base.getC_SubAcct_ID(), asDefaultAccts.getC_AcctSchema_ID(), base.getAccount_ID(), base.getC_SubAcct_ID(),
base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(), base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(),
base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(), base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(),
base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(), base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(),
base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID()); base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID());
line.setDescription(Msg.getElement(getCtx(), "UnrealizedGain_Acct")); line.setDescription(Msg.getElement(getCtx(), "UnrealizedGain_Acct"));
line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID()); line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID());
line.setAmtSourceCr (drTotal); line.setAmtSourceCr (drTotal);
line.setAmtAcctCr (drTotal); line.setAmtAcctCr (drTotal);
line.save(); line.save();
} }
// DR Entry = Loss // DR Entry = Loss
if (crTotal.signum() != 0) if (crTotal.signum() != 0)
{ {
MJournalLine line = new MJournalLine(journal); MJournalLine line = new MJournalLine(journal);
line.setLine(lineNo+2); line.setLine(lineNo+2);
MAccount base = MAccount.get(getCtx(), asDefaultAccts.getUnrealizedLoss_Acct()); MAccount base = MAccount.get(getCtx(), asDefaultAccts.getUnrealizedLoss_Acct());
MAccount acct = MAccount.get(getCtx(), asDefaultAccts.getAD_Client_ID(), AD_Org_ID, MAccount acct = MAccount.get(getCtx(), asDefaultAccts.getAD_Client_ID(), AD_Org_ID,
asDefaultAccts.getC_AcctSchema_ID(), base.getAccount_ID(), base.getC_SubAcct_ID(), asDefaultAccts.getC_AcctSchema_ID(), base.getAccount_ID(), base.getC_SubAcct_ID(),
base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(), base.getM_Product_ID(), base.getC_BPartner_ID(), base.getAD_OrgTrx_ID(),
base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(), base.getC_LocFrom_ID(), base.getC_LocTo_ID(), base.getC_SalesRegion_ID(),
base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(), base.getC_Project_ID(), base.getC_Campaign_ID(), base.getC_Activity_ID(),
base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID()); base.getUser1_ID(), base.getUser2_ID(), base.getUserElement1_ID(), base.getUserElement2_ID());
line.setDescription(Msg.getElement(getCtx(), "UnrealizedLoss_Acct")); line.setDescription(Msg.getElement(getCtx(), "UnrealizedLoss_Acct"));
line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID()); line.setC_ValidCombination_ID(acct.getC_ValidCombination_ID());
line.setAmtSourceDr (crTotal); line.setAmtSourceDr (crTotal);
line.setAmtAcctDr (crTotal); line.setAmtAcctDr (crTotal);
line.save(); line.save();
} }
} // createBalancing } // createBalancing
} // InvoiceNGL } // InvoiceNGL

View File

@ -19,6 +19,7 @@ package org.compiere.process;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.AdempiereUserError;
/** /**
@ -50,9 +51,11 @@ public class PaySelectionCreateCheck extends SvrProcess
else if (name.equals("PaymentRule")) else if (name.equals("PaymentRule"))
p_PaymentRule = (String)para[i].getParameter(); p_PaymentRule = (String)para[i].getParameter();
else else
log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
p_C_PaySelection_ID = getRecord_ID(); p_C_PaySelection_ID = getRecord_ID();
if (p_PaymentRule != null & p_PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDebit))
p_PaymentRule = null;
} // prepare } // prepare
/** /**
@ -62,7 +65,7 @@ public class PaySelectionCreateCheck extends SvrProcess
*/ */
protected String doIt () throws Exception protected String doIt () throws Exception
{ {
log.info ("doIt - C_PaySelection_ID=" + p_C_PaySelection_ID log.info ("C_PaySelection_ID=" + p_C_PaySelection_ID
+ ", PaymentRule=" + p_PaymentRule); + ", PaymentRule=" + p_PaymentRule);
MPaySelection psel = new MPaySelection (getCtx(), p_C_PaySelection_ID, get_TrxName()); MPaySelection psel = new MPaySelection (getCtx(), p_C_PaySelection_ID, get_TrxName());
@ -70,8 +73,6 @@ public class PaySelectionCreateCheck extends SvrProcess
throw new IllegalArgumentException("Not found C_PaySelection_ID=" + p_C_PaySelection_ID); throw new IllegalArgumentException("Not found C_PaySelection_ID=" + p_C_PaySelection_ID);
if (psel.isProcessed()) if (psel.isProcessed())
throw new IllegalArgumentException("@Processed@"); throw new IllegalArgumentException("@Processed@");
if (p_PaymentRule == null)
throw new IllegalArgumentException("No PaymentRule");
// //
MPaySelectionLine[] lines = psel.getLines(false); MPaySelectionLine[] lines = psel.getLines(false);
for (int i = 0; i < lines.length; i++) for (int i = 0; i < lines.length; i++)
@ -91,8 +92,9 @@ public class PaySelectionCreateCheck extends SvrProcess
/** /**
* Create Check from line * Create Check from line
* @param line * @param line
* @throws Exception for invalid bank accounts
*/ */
private void createCheck (MPaySelectionLine line) private void createCheck (MPaySelectionLine line) throws Exception
{ {
// Try to find one // Try to find one
for (int i = 0; i < m_list.size(); i++) for (int i = 0; i < m_list.size(); i++)
@ -103,22 +105,35 @@ public class PaySelectionCreateCheck extends SvrProcess
{ {
check.addLine(line); check.addLine(line);
if (!check.save()) if (!check.save())
throw new IllegalStateException("Cannot Save MPaySelectionCheck"); throw new IllegalStateException("Cannot save MPaySelectionCheck");
line.setC_PaySelectionCheck_ID(check.getC_PaySelectionCheck_ID()); line.setC_PaySelectionCheck_ID(check.getC_PaySelectionCheck_ID());
line.setProcessed(true); line.setProcessed(true);
if (!line.save()) if (!line.save())
throw new IllegalStateException("Cannot Save MPaySelectionLine"); throw new IllegalStateException("Cannot save MPaySelectionLine");
return; return;
} }
} }
// Create new // Create new
MPaySelectionCheck check = new MPaySelectionCheck(line, p_PaymentRule); String PaymentRule = line.getPaymentRule();
if (p_PaymentRule != null)
{
if (!X_C_Order.PAYMENTRULE_DirectDebit.equals(PaymentRule))
PaymentRule = p_PaymentRule;
}
MPaySelectionCheck check = new MPaySelectionCheck(line, PaymentRule);
if (!check.isValid())
{
int C_BPartner_ID = check.getC_BPartner_ID();
MBPartner bp = MBPartner.get(getCtx(), C_BPartner_ID);
String msg = "@NotFound@ @C_BP_BankAccount@: " + bp.getName();
throw new AdempiereUserError(msg);
}
if (!check.save()) if (!check.save())
throw new IllegalStateException("Cannot Save MPaySelectionCheck"); throw new IllegalStateException("Cannot save MPaySelectionCheck");
line.setC_PaySelectionCheck_ID(check.getC_PaySelectionCheck_ID()); line.setC_PaySelectionCheck_ID(check.getC_PaySelectionCheck_ID());
line.setProcessed(true); line.setProcessed(true);
if (!line.save()) if (!line.save())
throw new IllegalStateException("Cannot Save MPaySelectionLine"); throw new IllegalStateException("Cannot save MPaySelectionLine");
m_list.add(check); m_list.add(check);
} // createCheck } // createCheck

View File

@ -3,236 +3,236 @@
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it * * This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published * * under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope * * by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. * * See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along * * You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., * * with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us * * For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html * * or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/ *****************************************************************************/
package org.compiere.process; package org.compiere.process;
import java.math.*; import java.math.*;
import java.sql.*; import java.sql.*;
import java.util.logging.*; import java.util.logging.*;
import org.compiere.model.*; import org.compiere.model.*;
import org.compiere.util.*; import org.compiere.util.*;
/** /**
* Create Payment Selection Lines from AP Invoices * Create Payment Selection Lines from AP Invoices
* *
* @author Jorg Janke * @author Jorg Janke
* @version $Id: PaySelectionCreateFrom.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $ * @version $Id: PaySelectionCreateFrom.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/ */
public class PaySelectionCreateFrom extends SvrProcess public class PaySelectionCreateFrom extends SvrProcess
{ {
/** Only When Discount */ /** Only When Discount */
private boolean p_OnlyDiscount = false; private boolean p_OnlyDiscount = false;
/** Only when Due */ /** Only when Due */
private boolean p_OnlyDue = false; private boolean p_OnlyDue = false;
/** Include Disputed */ /** Include Disputed */
private boolean p_IncludeInDispute = false; private boolean p_IncludeInDispute = false;
/** Match Requirement */ /** Match Requirement */
private String p_MatchRequirement = "N"; private String p_MatchRequirement = "N";
/** Payment Rule */ /** Payment Rule */
private String p_PaymentRule = null; private String p_PaymentRule = null;
/** BPartner */ /** BPartner */
private int p_C_BPartner_ID = 0; private int p_C_BPartner_ID = 0;
/** BPartner Group */ /** BPartner Group */
private int p_C_BP_Group_ID = 0; private int p_C_BP_Group_ID = 0;
/** Payment Selection */ /** Payment Selection */
private int p_C_PaySelection_ID = 0; private int p_C_PaySelection_ID = 0;
/** /**
* Prepare - e.g., get Parameters. * Prepare - e.g., get Parameters.
*/ */
protected void prepare() protected void prepare()
{ {
ProcessInfoParameter[] para = getParameter(); ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++) for (int i = 0; i < para.length; i++)
{ {
String name = para[i].getParameterName(); String name = para[i].getParameterName();
if (para[i].getParameter() == null) if (para[i].getParameter() == null)
; ;
else if (name.equals("OnlyDiscount")) else if (name.equals("OnlyDiscount"))
p_OnlyDiscount = "Y".equals(para[i].getParameter()); p_OnlyDiscount = "Y".equals(para[i].getParameter());
else if (name.equals("OnlyDue")) else if (name.equals("OnlyDue"))
p_OnlyDue = "Y".equals(para[i].getParameter()); p_OnlyDue = "Y".equals(para[i].getParameter());
else if (name.equals("IncludeInDispute")) else if (name.equals("IncludeInDispute"))
p_IncludeInDispute = "Y".equals(para[i].getParameter()); p_IncludeInDispute = "Y".equals(para[i].getParameter());
else if (name.equals("MatchRequirement")) else if (name.equals("MatchRequirement"))
p_MatchRequirement = (String)para[i].getParameter(); p_MatchRequirement = (String)para[i].getParameter();
else if (name.equals("PaymentRule")) else if (name.equals("PaymentRule"))
p_PaymentRule = (String)para[i].getParameter(); p_PaymentRule = (String)para[i].getParameter();
else if (name.equals("C_BPartner_ID")) else if (name.equals("C_BPartner_ID"))
p_C_BPartner_ID = para[i].getParameterAsInt(); p_C_BPartner_ID = para[i].getParameterAsInt();
else if (name.equals("C_BP_Group_ID")) else if (name.equals("C_BP_Group_ID"))
p_C_BP_Group_ID = para[i].getParameterAsInt(); p_C_BP_Group_ID = para[i].getParameterAsInt();
else else
log.log(Level.SEVERE, "Unknown Parameter: " + name); log.log(Level.SEVERE, "Unknown Parameter: " + name);
} }
p_C_PaySelection_ID = getRecord_ID(); p_C_PaySelection_ID = getRecord_ID();
} // prepare } // prepare
/** /**
* Perrform process. * Perrform process.
* @return Message * @return Message
* @throws Exception if not successful * @throws Exception if not successful
*/ */
protected String doIt() throws Exception protected String doIt() throws Exception
{ {
log.info ("C_PaySelection_ID=" + p_C_PaySelection_ID log.info ("C_PaySelection_ID=" + p_C_PaySelection_ID
+ ", OnlyDiscount=" + p_OnlyDiscount + ", OnlyDue=" + p_OnlyDue + ", OnlyDiscount=" + p_OnlyDiscount + ", OnlyDue=" + p_OnlyDue
+ ", IncludeInDispute=" + p_IncludeInDispute + ", IncludeInDispute=" + p_IncludeInDispute
+ ", MatchRequirement=" + p_MatchRequirement + ", MatchRequirement=" + p_MatchRequirement
+ ", PaymentRule=" + p_PaymentRule + ", PaymentRule=" + p_PaymentRule
+ ", C_BP_Group_ID=" + p_C_BP_Group_ID + ", C_BPartner_ID=" + p_C_BPartner_ID); + ", C_BP_Group_ID=" + p_C_BP_Group_ID + ", C_BPartner_ID=" + p_C_BPartner_ID);
MPaySelection psel = new MPaySelection (getCtx(), p_C_PaySelection_ID, get_TrxName()); MPaySelection psel = new MPaySelection (getCtx(), p_C_PaySelection_ID, get_TrxName());
if (psel.get_ID() == 0) if (psel.get_ID() == 0)
throw new IllegalArgumentException("Not found C_PaySelection_ID=" + p_C_PaySelection_ID); throw new IllegalArgumentException("Not found C_PaySelection_ID=" + p_C_PaySelection_ID);
if (psel.isProcessed()) if (psel.isProcessed())
throw new IllegalArgumentException("@Processed@"); throw new IllegalArgumentException("@Processed@");
// psel.getPayDate(); // psel.getPayDate();
String sql = "SELECT C_Invoice_ID," String sql = "SELECT C_Invoice_ID,"
// Open // Open
+ " currencyConvert(invoiceOpen(i.C_Invoice_ID, 0)" + " currencyConvert(invoiceOpen(i.C_Invoice_ID, 0)"
+ ",i.C_Currency_ID, ?,?, i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID)," // ##1/2 Currency_To,PayDate + ",i.C_Currency_ID, ?,?, i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID)," // ##1/2 Currency_To,PayDate
// Discount // Discount
+ " currencyConvert(paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?)" // ##3 PayDate + " currencyConvert(paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?)" // ##3 PayDate
+ ",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID)," // ##4/5 Currency_To,PayDate + ",i.C_Currency_ID, ?,?,i.C_ConversionType_ID,i.AD_Client_ID,i.AD_Org_ID)," // ##4/5 Currency_To,PayDate
+ " PaymentRule, IsSOTrx " + " PaymentRule, IsSOTrx " // 4..6
+ "FROM C_Invoice i " + "FROM C_Invoice i "
+ "WHERE IsSOTrx='N' AND IsPaid='N' AND DocStatus IN ('CO','CL')" + "WHERE IsSOTrx='N' AND IsPaid='N' AND DocStatus IN ('CO','CL')"
+ " AND AD_Client_ID=?" // ##6 + " AND AD_Client_ID=?" // ##6
// Existing Payments - Will reselect Invoice if prepared but not paid // Existing Payments - Will reselect Invoice if prepared but not paid
+ " AND NOT EXISTS (SELECT * FROM C_PaySelectionLine psl " + " AND NOT EXISTS (SELECT * FROM C_PaySelectionLine psl "
+ "WHERE i.C_Invoice_ID=psl.C_Invoice_ID AND psl.IsActive='Y'" + "WHERE i.C_Invoice_ID=psl.C_Invoice_ID AND psl.IsActive='Y'"
+ " AND psl.C_PaySelectionCheck_ID IS NOT NULL)"; + " AND psl.C_PaySelectionCheck_ID IS NOT NULL)";
// Disputed // Disputed
if (!p_IncludeInDispute) if (!p_IncludeInDispute)
sql += " AND i.IsInDispute='N'"; sql += " AND i.IsInDispute='N'";
// PaymentRule (optional) // PaymentRule (optional)
if (p_PaymentRule != null) if (p_PaymentRule != null)
sql += " AND PaymentRule=?"; // ## sql += " AND PaymentRule=?"; // ##
// OnlyDiscount // OnlyDiscount
if (p_OnlyDiscount) if (p_OnlyDiscount)
{ {
if (p_OnlyDue) if (p_OnlyDue)
sql += " AND ("; sql += " AND (";
else else
sql += " AND "; sql += " AND ";
sql += "paymentTermDiscount(invoiceOpen(C_Invoice_ID, 0), C_Currency_ID, C_PaymentTerm_ID, DateInvoiced, ?) > 0"; // ## sql += "paymentTermDiscount(invoiceOpen(C_Invoice_ID, 0), C_Currency_ID, C_PaymentTerm_ID, DateInvoiced, ?) > 0"; // ##
} }
// OnlyDue // OnlyDue
if (p_OnlyDue) if (p_OnlyDue)
{ {
if (p_OnlyDiscount) if (p_OnlyDiscount)
sql += " OR "; sql += " OR ";
else else
sql += " AND "; sql += " AND ";
sql += "paymentTermDueDays(C_PaymentTerm_ID, DateInvoiced, ?) >= 0"; // ## sql += "paymentTermDueDays(C_PaymentTerm_ID, DateInvoiced, ?) >= 0"; // ##
if (p_OnlyDiscount) if (p_OnlyDiscount)
sql += ")"; sql += ")";
} }
// Business Partner // Business Partner
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
sql += " AND C_BPartner_ID=?"; // ## sql += " AND C_BPartner_ID=?"; // ##
// Business Partner Group // Business Partner Group
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
sql += " AND EXISTS (SELECT * FROM C_BPartner bp " sql += " AND EXISTS (SELECT * FROM C_BPartner bp "
+ "WHERE bp.C_BPartner_ID=i.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ## + "WHERE bp.C_BPartner_ID=i.C_BPartner_ID AND bp.C_BP_Group_ID=?)"; // ##
// PO Matching Requiremnent // PO Matching Requiremnent
if (p_MatchRequirement.equals("P") || p_MatchRequirement.equals("B")) if (p_MatchRequirement.equals("P") || p_MatchRequirement.equals("B"))
{ {
sql += " AND EXISTS (SELECT * FROM C_InvoiceLine il " sql += " AND EXISTS (SELECT * FROM C_InvoiceLine il "
+ "WHERE i.C_Invoice_ID=il.C_Invoice_ID" + "WHERE i.C_Invoice_ID=il.C_Invoice_ID"
+ " AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchPO m " + " AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchPO m "
+ "WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"; + "WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))";
} }
// Receipt Matching Requiremnent // Receipt Matching Requiremnent
if (p_MatchRequirement.equals("R") || p_MatchRequirement.equals("B")) if (p_MatchRequirement.equals("R") || p_MatchRequirement.equals("B"))
{ {
sql += " AND EXISTS (SELECT * FROM C_InvoiceLine il " sql += " AND EXISTS (SELECT * FROM C_InvoiceLine il "
+ "WHERE i.C_Invoice_ID=il.C_Invoice_ID" + "WHERE i.C_Invoice_ID=il.C_Invoice_ID"
+ " AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchInv m " + " AND QtyInvoiced=(SELECT SUM(Qty) FROM M_MatchInv m "
+ "WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))"; + "WHERE il.C_InvoiceLine_ID=m.C_InvoiceLine_ID))";
} }
// //
int lines = 0; int lines = 0;
int C_CurrencyTo_ID = psel.getC_Currency_ID(); int C_CurrencyTo_ID = psel.getC_Currency_ID();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try try
{ {
pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt = DB.prepareStatement (sql, get_TrxName());
int index = 1; int index = 1;
pstmt.setInt (index++, C_CurrencyTo_ID); pstmt.setInt (index++, C_CurrencyTo_ID);
pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setTimestamp(index++, psel.getPayDate());
// //
pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setTimestamp(index++, psel.getPayDate());
pstmt.setInt (index++, C_CurrencyTo_ID); pstmt.setInt (index++, C_CurrencyTo_ID);
pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setTimestamp(index++, psel.getPayDate());
// //
pstmt.setInt(index++, psel.getAD_Client_ID()); pstmt.setInt(index++, psel.getAD_Client_ID());
if (p_PaymentRule != null) if (p_PaymentRule != null)
pstmt.setString(index++, p_PaymentRule); pstmt.setString(index++, p_PaymentRule);
if (p_OnlyDiscount) if (p_OnlyDiscount)
pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setTimestamp(index++, psel.getPayDate());
if (p_OnlyDue) if (p_OnlyDue)
pstmt.setTimestamp(index++, psel.getPayDate()); pstmt.setTimestamp(index++, psel.getPayDate());
if (p_C_BPartner_ID != 0) if (p_C_BPartner_ID != 0)
pstmt.setInt (index++, p_C_BPartner_ID); pstmt.setInt (index++, p_C_BPartner_ID);
else if (p_C_BP_Group_ID != 0) else if (p_C_BP_Group_ID != 0)
pstmt.setInt (index++, p_C_BP_Group_ID); pstmt.setInt (index++, p_C_BP_Group_ID);
// //
ResultSet rs = pstmt.executeQuery (); ResultSet rs = pstmt.executeQuery ();
while (rs.next ()) while (rs.next ())
{ {
int C_Invoice_ID = rs.getInt(1); int C_Invoice_ID = rs.getInt(1);
BigDecimal PayAmt = rs.getBigDecimal(2); BigDecimal PayAmt = rs.getBigDecimal(2);
if (C_Invoice_ID == 0 || Env.ZERO.compareTo(PayAmt) == 0) if (C_Invoice_ID == 0 || Env.ZERO.compareTo(PayAmt) == 0)
continue; continue;
BigDecimal DiscountAmt = rs.getBigDecimal(3); BigDecimal DiscountAmt = rs.getBigDecimal(3);
String PaymentRule = rs.getString(4); String PaymentRule = rs.getString(4);
boolean isSOTrx = "Y".equals(rs.getString(5)); boolean isSOTrx = "Y".equals(rs.getString(5));
// //
lines++; lines++;
MPaySelectionLine pselLine = new MPaySelectionLine (psel, lines*10, PaymentRule); MPaySelectionLine pselLine = new MPaySelectionLine (psel, lines*10, PaymentRule);
pselLine.setInvoice (C_Invoice_ID, isSOTrx, pselLine.setInvoice (C_Invoice_ID, isSOTrx,
PayAmt, PayAmt.subtract(DiscountAmt), DiscountAmt); PayAmt, PayAmt.subtract(DiscountAmt), DiscountAmt);
if (!pselLine.save()) if (!pselLine.save())
{ {
pstmt.close(); pstmt.close();
throw new IllegalStateException ("Cannot save MPaySelectionLine"); throw new IllegalStateException ("Cannot save MPaySelectionLine");
} }
} }
rs.close (); rs.close ();
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
log.log(Level.SEVERE, "doIt - " + sql, e); log.log(Level.SEVERE, sql, e);
} }
try try
{ {
if (pstmt != null) if (pstmt != null)
pstmt.close (); pstmt.close ();
pstmt = null; pstmt = null;
} }
catch (Exception e) catch (Exception e)
{ {
pstmt = null; pstmt = null;
} }
return "@C_PaySelectionLine_ID@ - #" + lines; return "@C_PaySelectionLine_ID@ - #" + lines;
} // doIt } // doIt
} // PaySelectionCreateFrom } // PaySelectionCreateFrom