move branch adempire311 to trunk

This commit is contained in:
vpj-cd 2006-11-17 03:05:26 +00:00
parent ba85908c4f
commit 70fef6c478
525 changed files with 143596 additions and 0 deletions

13
base/.classpath Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="/print"/>
<classpathentry kind="src" path="/tools"/>
<classpathentry kind="src" path="/dbPort"/>
<classpathentry kind="var" path="JUNIT_HOME/junit.jar"/>
<classpathentry kind="src" path="/looks"/>
<classpathentry kind="lib" path="/interfaces/Interfaces.jar" sourcepath="/interfaces/src"/>
<classpathentry kind="lib" path="/tools/lib/commons-net-1.4.0.jar"/>
<classpathentry kind="output" path="build"/>
</classpath>

2
base/.packaging Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<configurations/>

26
base/.project Normal file
View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>base</name>
<comment></comment>
<projects>
<project>dbPort</project>
<project>looks</project>
<project>print</project>
<project>tools</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.ibm.etools.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,3 @@
#Sat Dec 17 10:51:04 PST 2005
eclipse.preferences.version=1
encoding//src/org/adempiere/model/MAttributeSetInstance.java=UTF-8

2
base/.xdoclet Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<configurations/>

29
base/Base.html Normal file
View File

@ -0,0 +1,29 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<TITLE>Project Base.jpx</TITLE>
</HEAD>
<BODY>
<H1>Project Notes</H1>
<HR>
<STRONG>Project: </STRONG>Base Functionality for Server and Client<BR>
<STRONG>Author: </STRONG>Jorg Janke<BR>
<STRONG>Version: </STRONG>$Id: Base.html,v 1.1 2006/04/21 17:41:36 jjanke Exp $
<hr>
<STRONG>Description: </STRONG>
<p>
The project creates the jar file <b>Adempiere/base/Base.jar</b>, which is included
in Server and Client jars (i.e. not directly distributed to minimize number of jars).
</p>
<hr>
<STRONG>Things to do... </STRONG><BR>
<UL>
<!-- Edit this section to keep track of your to do items -->
<LI>Item 1
<LI>Item 2
</UL>
</BODY>
</HTML>

20
base/RUN_build.bat Normal file
View File

@ -0,0 +1,20 @@
@Title Build Base
@Rem $Header: /cvsroot/adempiere/base/RUN_build.bat,v 1.10 2005/09/16 00:48:27 jjanke Exp $
@Echo off
@CALL ..\utils_dev\myDevEnv.bat
@IF NOT %ADEMPIERE_ENV%==Y GOTO NOBUILD
@echo Cleanup ...
@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main clean
@echo Building ...
@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main dist
@Echo Done ...
@sleep 60
@exit
:NOBUILD
@Echo Check myDevEnv.bat (copy from myDevEnvTemplate.bat)
@Pause

18
base/RUN_build.sh Normal file
View File

@ -0,0 +1,18 @@
# Module compiling script
# Ported from Windows script Marek Mosiewicz<marek.mosiewicz@jotel.com.pl>
SAVED_DIR=`pwd` #save current dir
cd `dirname $0`/../utils_dev #change dir to place where script resides - doesn not work with sym links
UTILS_DEV=`pwd` #this is adempiere source
cd $SAVED_DIR #back to the saved directory
. $UTILS_DEV/myDevEnv.sh #call environment
echo done
if [ ! $ADEMPIERE_ENV==Y ] ; then
echo "Can't set developemeent environemnt - check myDevEnv.sh"
exit 1
fi
echo running Ant
$JAVA_HOME/bin/java -Dant.home="." $ANT_PROPERTIES org.apache.tools.ant.Main

88
base/build.xml Normal file
View File

@ -0,0 +1,88 @@
<!-- ============================================= -->
<!-- Base -->
<!-- ============================================= -->
<!-- $Header: /cvs/adempiere/base/build.xml,v 1.1 2006/04/21 17:41:36 jjanke Exp $ -->
<project name="base" default="dist" basedir=".">
<description>
This buildfile is used to build the base subproject within
the Adempiere project.
</description>
<!-- set global properties for this build -->
<property name="src" value="src"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="."/>
<property name="jar.path" value="../lib"/>
<property name="jar.name" value="Base"/>
<!-- set path to include the necessary jar files for javac -->
<path id="project.class.path">
<pathelement path="${classpath}"/>
<pathelement path="${jar.path}/CCTools.jar"/>
<pathelement path="../dbPort/dbPort.jar"/>
<pathelement path="../looks/CLooks.jar"/>
<pathelement path="../print/Print.jar"/>
<pathelement path="../tools/lib/junit.jar"/>
<pathelement path="../tools/lib/j2ee.jar"/>
<pathelement path="../tools/lib/jnlp.jar"/>
<pathelement path="../interfaces/Interfaces.jar"/>
<pathelement path="../tools/lib/servlet.jar" />
</path>
<target name="init" description="initialization target">
<echo message="=========== Build Base"/>
<!-- create the time stamp -->
<tstamp/>
<!-- create the build directory structure used by compile -->
<mkdir dir="${build.dir}"/>
<!-- check for the distribution directory -->
<available file="${dist.dir}" type="dir" property="dist.dir.exists"/>
</target>
<target name="makedir" depends="init" unless="dist.dir.exists">
<!-- create the distribution directory if not available -->
<mkdir dir="${dist.dir}"/>
</target>
<target name="compile" depends="makedir">
<!-- compile the java code from ${src} into ${build.dir} -->
<javac srcdir="${src}" destdir="${build.dir}" deprecation="on" debug="on">
<classpath refid="project.class.path"/>
</javac>
<!-- copy all image & sound files from src to the build directory -->
<copy todir="${build.dir}">
<fileset dir="${src}">
<include name="**/images/*"/>
<include name="**/*.gif"/>
<include name="**/*.jpg"/>
<include name="**/*.wav"/>
<include name="**/*.htm"/>
<include name="**/*.html"/>
<include name="**/*.properties"/>
<exclude name="**/package.html"/>
</fileset>
</copy>
</target>
<!-- =========================================== -->
<!-- Distribution -->
<!-- =========================================== -->
<target name="dist" depends="compile">
<!-- put everything from ${build.dir} into the ${jar.name}.jar file -->
<jar jarfile="${dist.dir}/${jar.name}.jar" basedir="${build.dir}"/>
</target>
<target name="clean">
<!-- Delete the ${build.dir} directory trees -->
<delete dir="${build.dir}"/>
<delete file="${dist.dir}/${jar.name}.jar" failonerror="false"/>
</target>
</project>

5
base/documentation.bat Normal file
View File

@ -0,0 +1,5 @@
@Rem API Documentation for Base
call ..\doc\documentation.bat src doc -private
@pause

6
base/packages.txt Normal file
View File

@ -0,0 +1,6 @@
org.compiere
org.compiere.impexp
org.compiere.model
org.compiere.report.core
org.compiere.server
org.compiere.util

4
base/packaging-build.xml Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project default="_generation_" name="Packaging Generator">
<target name="_generation_" depends=""/>
</project>

View File

@ -0,0 +1,156 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere;
import java.math.*;
import java.util.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Base Library Test Classes mainly for Optimize it
*
* @author Jorg Janke
* @version $Id: Base.java,v 1.5 2006/09/21 20:44:54 jjanke Exp $
*/
class Base
{
/**
* Base Test
*/
public static void test()
{
System.out.println("** Before Init **"); //$NON-NLS-1$
getMemoryUsed();
Properties ctx = Login.initTest(false);
// Log.printProperties(System.getProperties(), "System", false);
//
System.gc(); // cleanup Init
//
System.out.println("** Before Creation **");
long start = getMemoryUsed();
// *******************************************************************
// Table=100, Shipper=142, Window=102, Reference=101
int AD_Window_ID = 102;
long startTime = System.currentTimeMillis();
GridWindowVO vo = GridWindowVO.create(Env.getCtx(), 1, AD_Window_ID);
GridWindow w = new GridWindow(vo);
long endDef = System.currentTimeMillis();
System.out.println("Load Definition Time in ms = " + String.valueOf(endDef-startTime));
if (1==2) // optional step
{
w.loadCompete();
long endDefComplete = System.currentTimeMillis();
System.out.println("Load Definition Complete Time in ms = " + String.valueOf(endDefComplete-startTime));
}
w.query();
long endData = System.currentTimeMillis();
System.out.println("Load Data Time in ms = " + String.valueOf(endData-startTime));
w.loadCompete();
long endDataComplete = System.currentTimeMillis();
System.out.println("Load Data Complete Time in ms = " + String.valueOf(endDataComplete-startTime));
w.getTab(0).navigate(0);
// *******************************************************************
// sleep();
System.out.println("** Before Dispose **");
getMemoryUsed();
w.dispose();
// sleep();
//
System.out.println("** Before GC **");
getMemoryUsed();
w = null;
System.gc();
System.out.println("** After GC **");
getMemoryUsed();
System.gc();
System.out.println("** Final **");
long complete = System.currentTimeMillis();
System.out.println("Complete Time in ms = " + String.valueOf(complete-startTime));
long end = getMemoryUsed();
System.out.println("Memory increase in kB = End-Start=" + String.valueOf((end-start)/1024));
listThreads();
//
System.out.println("API Test");
System.out.println("64.72=" + MConversionRate.convert(ctx, new BigDecimal(100.0), 116, 100,0,0));
System.out.println("0.647169=" + MConversionRate.getRate(116, 100, null, 0,0,0));
System.out.println("12.5=" + MUOMConversion.convert(101, 102, new BigDecimal(100.0), true));
} // Base
/**
* Get Used Memory in bytes
* @return memory used
*/
private static long getMemoryUsed()
{
long free = Runtime.getRuntime().freeMemory();
long total = Runtime.getRuntime().totalMemory();
long used = total - free;
//
System.out.println("Memory used in kB = Total("
+ String.valueOf(total/1024) + ")-Free("
+ String.valueOf(free/1024) + ") = " + String.valueOf(used/1024));
System.out.println("Active Threads=" + Thread.activeCount());
return used;
} // getMemoryUsed
/**
* Sleep for a second
*/
private static void sleep()
{
System.out.println(".. sleeping-ini .. -> " + Thread.activeCount());
Thread.yield();
try
{
Thread.sleep(1000);
}
catch (final InterruptedException ie)
{}
System.out.println(".. sleeping-end .. -> " + Thread.activeCount());
} // sleep
/**
* List Threads
*/
private static void listThreads()
{
Thread[] list = new Thread[Thread.activeCount()];
// int no = Thread.currentThread().enumerate(list);
for (int i = 0; i < list.length; i++)
{
if (list[i] != null)
System.out.println("Thread " + i + " - " + list[i].toString());
}
} // listThreads
/**
* Start
* @param args ignored
*/
public static void main(String[] args)
{
Base.test();
Env.exitEnv(0);
} // main
} // Base

View File

@ -0,0 +1,132 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
import org.compiere.model.*;
import org.compiere.print.*;
/**
* Migrate Data
* @author Jorg Janke
* @version $Id: MigrateData.java,v 1.3 2006/07/30 00:51:06 jjanke Exp $
*/
public class MigrateData
{
/**
* Migrate Data.
* Called from DB.afterMigration
*/
public MigrateData ()
{
release252c();
// Update existing Print Format
PrintFormatUtil pfu = new PrintFormatUtil (Env.getCtx());
pfu.addMissingColumns();
} // MigrateData
/** Logger */
private static CLogger log = CLogger.getCLogger (MigrateData.class);
/**
* Release 252c
*/
private void release252c()
{
String sql = "SELECT COUNT(*) FROM M_ProductDownload";
int no = DB.getSQLValue(null, sql);
if (no > 0)
{
log.finer("No Need - Downloads #" + no);
return;
}
//
int count = 0;
sql = "SELECT AD_Client_ID, AD_Org_ID, M_Product_ID, Name, DownloadURL "
+ "FROM M_Product "
+ "WHERE DownloadURL IS NOT NULL";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
int AD_Client_ID = rs.getInt(1);
int AD_Org_ID = rs.getInt(2);
int M_Product_ID = rs.getInt(3);
String Name = rs.getString(4);
String DownloadURL = rs.getString(5);
//
Properties ctx = new Properties (Env.getCtx());
Env.setContext(ctx, "#AD_Client_ID", AD_Client_ID);
Env.setContext(ctx, "AD_Client_ID", AD_Client_ID);
Env.setContext(ctx, "#AD_Org_ID", AD_Org_ID);
Env.setContext(ctx, "AD_Org_ID", AD_Org_ID);
MProductDownload pdl = new MProductDownload(ctx, 0, null);
pdl.setM_Product_ID(M_Product_ID);
pdl.setName(Name);
pdl.setDownloadURL(DownloadURL);
if (pdl.save())
{
count++;
String sqlUpdate = "UPDATE M_Product SET DownloadURL = NULL WHERE M_Product_ID=" + M_Product_ID;
int updated = DB.executeUpdate(sqlUpdate, null);
if (updated != 1)
log.warning("Product not updated");
}
else
log.warning("Product Download not created M_Product_ID=" + M_Product_ID);
}
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;
}
log.info("#" + count);
} // release252c
/**
* Migrate Data
* @param args ignored
*/
public static void main (String[] args)
{
Adempiere.startup(true);
new MigrateData();
} // main
} // MigrateData

View File

@ -0,0 +1,63 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.process.*;
/**
* Validate Container Stage
*
* @author Jorg Janke
* @version $Id: CStageValidate.java,v 1.3 2006/07/30 00:51:06 jjanke Exp $
*/
public class CStageValidate extends SvrProcess
{
private int p_CM_CStage_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
p_CM_CStage_ID = getRecord_ID();
} // prepare
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt ()
throws Exception
{
log.info("CM_CStage_ID=" + p_CM_CStage_ID);
MCStage stage = new MCStage (getCtx(), p_CM_CStage_ID, get_TrxName());
return stage.validate();
} // doIt
} // CStageValidate

View File

@ -0,0 +1,192 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import org.compiere.util.*;
import org.compiere.model.*;
/**
* The CacheHandler handles deployment and clean of internal and external caches
*
* @author Yves Sandfort
* @version $Id$
*/
public class CacheHandler {
protected String[] cacheURLs;
protected CLogger log;
/**
* CacheHandler for single URL environment
* @param thisURL URL of this Server
* @param tLog thisLogger
* @param ctx Propertie Context
* @param trxName Transaction
*/
public CacheHandler(String thisURL, CLogger tLog, Properties ctx, String trxName) {
int [] theseServers = X_CM_BroadcastServer.getAllIDs ("CM_BroadcastServer", "CM_WebProject_ID=0", trxName);
if (theseServers!=null && theseServers.length>0) {
String [] thisURLs = new String [theseServers.length];
for(int i=0;i<theseServers.length;i++) {
X_CM_BroadcastServer thisServer = new X_CM_BroadcastServer(ctx, theseServers[i] ,trxName);
thisURLs[i] = thisServer.getIP_Address ();
}
cacheURLs = thisURLs;
} else {
// Okay we can't find any cluster config, so we will use the AppsServer from Client
String [] thisURLs = new String[1];
thisURLs[0] = thisURL;
cacheURLs = thisURLs;
}
log = tLog;
}
/**
* CacheHandler form multiple URLs
* @param thisURLs Array of Cache Server URLs
* @param tLog Logger
*/
public CacheHandler(String [] thisURLs, CLogger tLog) {
log = tLog;
cacheURLs = thisURLs;
}
/**
* Clean Template cache for this ID
* @param ID ID of template to clean
*/
public void cleanTemplate(Integer ID) {
cleanTemplate("" + ID);
}
/**
* Clean Template cache for this ID
* @param ID ID of template to clean
*/
public void cleanTemplate(String ID) {
runURLRequest("Template", ID);
}
/**
* Empty all Template Caches
*/
public void emptyTemplate() {
runURLRequest("Template", "0");
}
/**
* Clean ContainerCache for this ID
* @param ID for Container to clean
*/
public void cleanContainer(Integer ID) {
cleanContainer("" + ID);
}
/**
* Clean ContainerCache for this ID
* @param ID for container to clean
*/
public void cleanContainer(String ID) {
runURLRequest("Container", ID);
}
/**
* Clean ContainerTreeCache for this WebProjectID
* @param ID for Container to clean
*/
public void cleanContainerTree(Integer ID) {
cleanContainerTree("" + ID);
}
/**
* Clean ContainerTreeCache for this WebProjectID
* @param ID for container to clean
*/
public void cleanContainerTree(String ID) {
runURLRequest("ContainerTree", ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(Integer ID) {
cleanContainerElement("" + ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(String ID) {
runURLRequest("ContainerElement", ID);
}
private void runURLRequest(String cache, String ID) {
String thisURL = null;
for(int i=0; i<cacheURLs.length; i++) {
try {
thisURL = "http://" + cacheURLs[i] + "/cache/Service?Cache=" + cache + "&ID=" + ID;
URL url = new URL(thisURL);
Proxy thisProxy = Proxy.NO_PROXY;
URLConnection urlConn = url.openConnection(thisProxy);
urlConn.setUseCaches(false);
urlConn.connect();
Reader stream = new java.io.InputStreamReader(
urlConn.getInputStream());
StringBuffer srvOutput = new StringBuffer();
try {
int c;
while ( (c=stream.read()) != -1 )
srvOutput.append( (char)c );
} catch (Exception E2) {
E2.printStackTrace();
}
} catch (IOException E) {
if (log!=null)
log.warning("Can't clean cache at:" + thisURL + " be carefull, your deployment server may use invalid or old cache data!");
}
}
}
/**
* Converts JNP URL to http URL for cache cleanup
* @param JNPURL String with JNP URL from Context
* @return clean servername
*/
public static String convertJNPURLToCacheURL(String JNPURL) {
if (JNPURL.indexOf("jnp://")>=0) {
JNPURL = JNPURL.substring(JNPURL.indexOf("jnp://")+6);
}
if (JNPURL.indexOf(":")>=0) {
JNPURL = JNPURL.substring(0,JNPURL.indexOf(":"));
}
if (JNPURL.length()>0) {
return JNPURL;
} else {
return null;
}
}
}

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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
import org.compiere.model.*;
/**
* Template
*
* @author Yves Sandfort
* @version $Id$
*/
public class CalloutTemplate extends CalloutEngine
{
/**
* Invoice Line - Charge.
* - updates PriceActual from Charge
* - sets PriceLimit, PriceList to zero
* Calles tax
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String invalidate (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
// Summary ?
if (mTab.getValue("IsSummary")!=null)
{
mTab.setValue("IsValid", false);
return "";
}
return "";
} // charge
} // CalloutTemplate

View File

@ -0,0 +1,27 @@
/******************************************************************************
* 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.adempiere.org/license.html
* 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@adempiere.org
*****************************************************************************/
package org.compiere.cm;
/**
*
*
* @author Yves Sandfort
* @version $Id$
*/
public class MediaDirectDeploy
{
}

View File

@ -0,0 +1,307 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* @author Yves Sandfort
* @version $Revision$
*/
/**
* StringUtil is a helper class to run different String managements not implemented in Java Core
*
* @author Yves Sandfort
* @version $id$
*
*/
public class StringUtil {
/**
* Replace all occurences of search with replace in original
* @param original the original String
* @param search the string to look for
* @param replace the string we will replace search with
* @return StringBuffer with result
*/
public static StringBuffer replace(StringBuffer original, String search, String replace) {
return doReplace (original, search, replace, false, true);
}
/**
* Replace all occurences of search with replace in original
* @param original the original String
* @param search the string to look for
* @param replace the string we will replace search with
* @return String with result, null will get replaced by ""
*/
public static String replace (String original, String search, String replace) {
if (original==null) original = "";
return doReplace (new StringBuffer(original), search, replace, false, true).toString();
}
/**
* Replace all occurences of search with replace in original
* @param original the original String
* @param search the string to look for
* @param replace the string we will replace search with
* @return String with result, null will get replaced by ""
*/
public static String replace (String original, char search, String replace) {
if (original==null) original = "";
return doReplace (new StringBuffer(original), search, replace, true).toString();
}
/**
* Replace all or one occurence of search with replace in original
* @param original the original StringBuffer
* @param search String to get replaced
* @param replace String to replace
* @param ignoreCase should we ignore cases
* @param allOccurences should all Occurences get replaced
* @return StringBuffer with result
*/
public static StringBuffer replace(StringBuffer original, String search, String replace, boolean ignoreCase, boolean allOccurences) {
return doReplace (original, search, replace, ignoreCase, allOccurences);
}
/**
* Replace all or one occurence of search with replace in original
* @param original the original StringBuffer
* @param search String to get replaced
* @param replace String to replace
* @param ignoreCase should we ignore cases
* @param allOccurences should all Occurences get replaced
* @return StringBuffer with result
*/
public static String replace(String original, String search, String replace, boolean ignoreCase, boolean allOccurences) {
if (original==null) original="";
return replace(new StringBuffer(original), search, replace, ignoreCase, allOccurences).toString();
}
/**
* Replace one occurence of search with replace in original
* @param original StringBuffer
* @param search String to look for
* @param replace String to replace search with
* @return new StringBuffer with result
*/
public static StringBuffer replaceOne(StringBuffer original, String search, String replace) {
if (original.toString().indexOf(search)>=0) {
original.replace(original.toString().indexOf(search),original.toString().indexOf(search)+search.length(),replace);
}
return original;
}
/**
* Replace one occurence of search with replace in original
* @param original String to look in
* @param search String to search for
* @param replace String to replace search with
* @return new String with result
*/
public static String replaceOne(String original, String search, String replace) {
StringBuffer toriginal = new StringBuffer(original);
if (toriginal.toString().indexOf(search)>=0) {
toriginal.replace(toriginal.toString().indexOf(search),toriginal.toString().indexOf(search)+search.length(),replace);
}
return toriginal.toString();
}
/**
* Run RegEx Expression against original String
* @param original StringBuffer with original context
* @param regex Regular Expression to run as query
* @param replace Replace String
* @param CASE_INSENSITIVE whether we should take care of case or not
* @return StringBuffer with result
*/
public static StringBuffer replaceRegex(StringBuffer original, String regex, String replace, boolean CASE_INSENSITIVE) {
int flags=0;
if (CASE_INSENSITIVE) flags=Pattern.CASE_INSENSITIVE;
Pattern p = Pattern.compile(regex, flags);
Matcher m = p.matcher(original);
StringBuffer newSB = new StringBuffer();
boolean result = m.find();
while(result) {
m.appendReplacement(newSB, replace);
result = m.find();
}
m.appendTail(newSB);
return newSB;
}
/**
* Run RegEx Expression against original String
* @param original StringBuffer with original context
* @param regex Regular Expression to run as query
* @param replace Replace String
* @param CASE_INSENSITIVE whether we should take care of case or not
* @return String with result
*/
public static String replaceRegex(String original, String regex, String replace, boolean CASE_INSENSITIVE) {
return replaceRegex(new StringBuffer(original), regex, replace, CASE_INSENSITIVE).toString();
}
private static StringBuffer doReplace(StringBuffer original, String alt, String neu, boolean ignoreCase, boolean allOccurences) {
int position = -1;
if (alt==null) alt="";
if (neu==null) neu="";
if (original==null) original = new StringBuffer("");
int altNeuDiff = neu.length()-alt.length();
if (neu.lastIndexOf(alt)>=altNeuDiff) altNeuDiff = neu.lastIndexOf(alt)+1;
if (ignoreCase) {
position = original.toString().toLowerCase().indexOf(alt.toLowerCase());
while (position>=0) {
original.replace(position,position + alt.length(),neu);
position = original.toString().toLowerCase().indexOf(alt.toLowerCase(),position+altNeuDiff);
}
} else {
position = original.toString().indexOf(alt);
while (position>=0) {
original.replace(position,position + alt.length(),neu);
position = original.toString().indexOf(alt,position+altNeuDiff);
}
}
return original;
}
private static StringBuffer doReplace(StringBuffer original, char alt, String neu, boolean allOccurences) {
int position = -1;
if (original==null) original = new StringBuffer("");
int altNeuDiff = neu.length()-1;
if (neu.lastIndexOf(alt)>=altNeuDiff) altNeuDiff = neu.lastIndexOf(alt)+1;
position = original.toString().indexOf(alt);
while (position>=0) {
original.replace(position,position + 1,neu);
position = original.toString().indexOf(alt,position+altNeuDiff);
}
return original;
}
/**
* This function will split a string based on a split character.
* @param searchIn The string to split
* @param splitter The separator
* @return String array of split values
*/
public static String[] split(String searchIn, String splitter) {
String[] results = new String[count(searchIn,splitter)+1];
int position=0;
int i=0;
while (searchIn.indexOf(splitter,position)>=0) {
results[i]=searchIn.substring(position,searchIn.indexOf(splitter,position+2));
position = searchIn.indexOf(splitter,position)+1;
i++;
}
results[(results.length-1)]=searchIn.substring(position);
return results;
}
/**
* Remove String toBeRemoved from oroginal
* @param original String to look in
* @param toBeRemoved String to get removed
* @param ignoreCase should we take care of case
* @return String without toBeRemoved
*/
public static String remove(String original, String toBeRemoved, boolean ignoreCase) {
String thisResult = null;
if (!toBeRemoved.equals("") && toBeRemoved!=null) {
thisResult = replace(original, toBeRemoved, "", ignoreCase, true);
}
return thisResult;
}
/**
* To split for indexes we will look for the next Word in tempstr
* @param tempStr to look into
* @return nextWord in String
*/
public static String getNextWord(String tempStr) {
String word = "";
if (tempStr.indexOf(" ")>=0) {
word=tempStr.substring(0,tempStr.indexOf(" "));
} else {
word=tempStr;
}
return word;
}
/**
* For some save scnearios and analysis we should remove special characters, i.e. HTML
* @param tempStr to remove Special Char
* @return new String without special chars
*/
public static String removeSpecialChar(String tempStr) {
if (tempStr!=null) {
tempStr=replace(tempStr,",","", true, true);
tempStr=replace(tempStr,".","", true, true);
tempStr=replace(tempStr,"!","", true, true);
tempStr=replace(tempStr,"?","", true, true);
tempStr=replace(tempStr,"'","", true, true);
tempStr=replace(tempStr,":","", true, true);
tempStr=replace(tempStr,"(","", true, true);
tempStr=replace(tempStr,")","", true, true);
tempStr=replace(tempStr,"+","", true, true);
tempStr=replace(tempStr,"-","", true, true);
tempStr=replace(tempStr,">","", true, true);
tempStr=replace(tempStr,"<","", true, true);
tempStr=replace(tempStr,"/","", true, true);
while (tempStr.indexOf(" ")>0) {
tempStr=replace(tempStr," "," ", true, true);
}
tempStr=replace(tempStr," "," ", true, true);
}
return tempStr;
}
/**
* Should return you the number of occurences of "find" in "orig
* @param orig The String to look in
* @param find The String to look for
* @return Number of occurences, 0 if none
*/
public static int count(String orig, String find) {
int retVal = 0;
int pos = 0;
while (orig.indexOf(find,pos)>0) {
pos = orig.indexOf(find,pos)+1;
retVal++;
}
return retVal;
}
/**
* Gnerate CRC String for tempStr
* @param tempStr
* @return CRC Code for tempStr
* @throws IOException
*/
public static String crc(String tempStr) throws IOException {
java.util.zip.Adler32 inChecker = new java.util.zip.Adler32();
java.util.zip.CheckedInputStream in = null;
in = new java.util.zip.CheckedInputStream(new java.io.ByteArrayInputStream(tempStr.getBytes()), inChecker);
@SuppressWarnings("unused") int c;
while ((c = in.read()) != -1) c=0;
String myCheckSum = "" + inChecker.getValue();
return myCheckSum;
}
}

View File

@ -0,0 +1,57 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.util.logging.Level;
import org.compiere.process.*;
import org.compiere.model.*;
/**
* CM Template Validation Process
*
* @author Jorg Janke
* @version $Id: TemplateValidate.java,v 1.3 2006/08/08 13:29:49 comdivision Exp $
*/
public class TemplateValidate extends SvrProcess
{
@Override
protected void prepare ()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
//else if (name.equals("CM_WebProject_ID"))
//p_CM_WebProject_ID = ((BigDecimal)para[i].getParameter()).intValue();
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
} // prepare
@Override
protected String doIt ()
throws Exception
{
MTemplate thisTemplate = new MTemplate(getCtx (), getRecord_ID (), get_TrxName ());
thisTemplate.setIsValid (true);
thisTemplate.save ();
return null;
}
} // TemplateValidate

View File

@ -0,0 +1,185 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.cm;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.process.*;
import org.compiere.util.*;
/**
* Deploy Web Project
*
* @author Jorg Janke
* @version $Id: WebProjectDeploy.java,v 1.10 2006/09/04 21:21:31 comdivision Exp $
*/
public class WebProjectDeploy extends SvrProcess
{
/** WebProject */
private int p_CM_WebProject_ID = 0;
/** Project */
private MWebProject m_project = null;
/** Stage Hash Map */
private HashMap<Integer, MCStage> m_map = new HashMap<Integer, MCStage>();
/** List of IDs */
private ArrayList <Integer> m_idList = new ArrayList<Integer>();
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("CM_WebProject_ID"))
p_CM_WebProject_ID = para[i].getParameterAsInt();
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
} // prepare
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt ()
throws Exception
{
org.compiere.cm.CacheHandler thisHandler = new org.compiere.cm.CacheHandler(org.compiere.cm.CacheHandler.convertJNPURLToCacheURL(getCtx().getProperty("java.naming.provider.url")), log, getCtx(), get_TrxName());
log.info("CM_WebProject_ID=" + p_CM_WebProject_ID);
m_project = new MWebProject(getCtx(), p_CM_WebProject_ID, get_TrxName());
if (m_project.get_ID() != p_CM_WebProject_ID)
throw new AdempiereUserError("@NotFound@ @CM_WebProject_ID@ " + p_CM_WebProject_ID);
// Deploy Media
MMedia[] media = MMedia.getMedia(m_project);
MMediaServer[] mserver = MMediaServer.getMediaServer(m_project);
for (int i = 0; i < mserver.length; i++)
mserver[i].deploy(media);
// Stage
MCStage[] stages = MCStage.getStages(m_project);
for (int i = 0; i < stages.length; i++)
m_map.put(new Integer(stages[i].getCM_CStage_ID()), stages[i]);
// Copy Stage Tree
MTree treeS = new MTree (getCtx(), m_project.getAD_TreeCMS_ID(), false, false, get_TrxName());
MTreeNode root = treeS.getRoot();
copyStage(root, "/");
// Delete Inactive Containers
MContainer[] containers = MContainer.getContainers(m_project);
for (int i = 0; i < containers.length; i++)
{
MContainer container = containers[i];
if (!m_idList.contains(new Integer(container.getCM_Container_ID())))
{
String name = container.getName();
if (container.delete(true))
log.fine("Deleted: " + name);
else // e.g. was referenced
{
log.warning("Failed Delete: " + name);
addLog(0,null,null, "@Error@ @Delete@: " + name);
}
}
// Remove Container from cache
thisHandler.cleanContainer(container.get_ID());
} // Delete Inactive
// Sync Stage & Container Tree
MTree_NodeCMS nodesCMS[] = MTree_NodeCMS.getTree(getCtx(), m_project.getAD_TreeCMS_ID(), get_TrxName());
MTree_NodeCMC nodesCMC[] = MTree_NodeCMC.getTree(getCtx(), m_project.getAD_TreeCMC_ID(), get_TrxName());
for (int s = 0; s < nodesCMS.length; s++)
{
MTree_NodeCMS nodeCMS = nodesCMS[s];
int Node_ID = nodeCMS.getNode_ID();
for (int c = 0; c < nodesCMC.length; c++)
{
MTree_NodeCMC nodeCMC = nodesCMC[c];
if (nodeCMC.getNode_ID() == Node_ID)
{
//if (nodeCMS.getParent_ID()!=0)
nodeCMC.setParent_ID(nodeCMS.getParent_ID());
nodeCMC.setSeqNo(nodeCMS.getSeqNo());
nodeCMC.save();
break;
}
}
} // for all stage nodes
// Clean ContainerTree Cache
thisHandler.cleanContainerTree (p_CM_WebProject_ID);
return "@Copied@ @CM_Container_ID@ #" + m_idList.size();
} // doIt
/**
* Copy Stage
* @param node node
* @param path path
*/
private void copyStage (MTreeNode node, String path)
{
org.compiere.cm.CacheHandler thisHandler = new org.compiere.cm.CacheHandler(org.compiere.cm.CacheHandler.convertJNPURLToCacheURL(getCtx().getProperty("java.naming.provider.url")), log, getCtx(), get_TrxName());
Integer ID = new Integer(node.getNode_ID());
MCStage stage = m_map.get(ID);
//
int size = node.getChildCount();
for (int i = 0; i < size; i++)
{
MTreeNode child = (MTreeNode)node.getChildAt(i);
ID = new Integer(child.getNode_ID());
stage = m_map.get(ID);
if (stage == null)
{
log.warning("Not Found ID=" + ID);
continue;
}
if (!stage.isActive())
continue;
//
if (stage != null && stage.isModified())
{
MContainer cc = MContainer.copy (m_project, stage, path);
if (cc != null)
{
addLog (0, null, null, "@Copied@: " + cc.getName());
m_idList.add(ID);
}
// Remove Container from cache
thisHandler.cleanContainer(cc.get_ID());
// Reset Modified flag...
stage.setIsModified(false);
stage.save(stage.get_TrxName());
}
if (child.isSummary())
copyStage (child, path + stage.getRelativeURL() + "/");
}
} // copyStage
} // WebProjectDeploy

View File

@ -0,0 +1,265 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import org.compiere.model.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
/**
* Interface to be implemented by bank statement loader classes
*
* Bank statement loader classes that extend this interface can be loaded
* by the MBankStatementLoader controller class.
* The usage patter looks like this:
*
* -init() is called in order to initialize the loader
*
* -validate() is called, allowing the loader to perform data validation if
* it provides this.
*
* -loadLines() is called, request the loader to start loading statement lines
*
* -for everu statement line that the loader encounteres, it calls the
* saveLine() method of the MBankStatement controller object it obtained
* as part of the call to init()
*
* -The MBankStatementLoader controller object can now obtain the data for the current bank
* statement line by using the corresponding get methods of the loader class.
*
* @author Maarten Klinker, Eldir Tomassen
* @version $Id: BankStatementLoaderInterface.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public interface BankStatementLoaderInterface
{
/**
* Initialize the loader
* @param controller Reference to the MBankStatementLoader controller object
* @return Initialized succesfully
*/
public boolean init(MBankStatementLoader controller);
/**
* Verify whether the data to be imported is valid
* @return Data is valid
* If the actual loaders does not do any validity checks
* it will just return true.
*/
public boolean isValid();
/**
* Start importing statement lines
* @return Statement lines imported succesfully
*/
public boolean loadLines();
/**
* Return the most recent error
* @return Error message
* This error message will be handled as a Adempiere message,
* (e.g. it can be translated)
*/
public String getLastErrorMessage();
/**
* Return the most recent error description
* @return Error discription
* This is an additional error description, it can be used to provided
* descriptive iformation, such as a file name or SQL error, that can not
* be translated by the Adempiere message system.
*/
public String getLastErrorDescription();
/**
* The last time this loader aquired bank statement data.
* For OFX this is the <DTEND> value. This is generally only available\
* after loadLines() has been called. If a specific loader class
* does not provided this information it is allowed to return null
* @return Date last run
*/
public Timestamp getDateLastRun();
/**
* The routing number of the bank account for the statement line.
* @return Routing number
*/
public String getRoutingNo();
/**
* The account number of the bank account for the statement line.
* @return Bank account number
*/
public String getBankAccountNo();
/**
* Additional reference information
* Statement level reference information. If a specific loader class
* does not provided this, it is allowed to return null.
* @return Error discription
*/
public String getStatementReference();
/**
* Statement Date
* Date of the bank statement. If a specific loader does not provide this,
* it is allowed to return null.
* @return Statement Date
*/
public Timestamp getStatementDate();
/**
* Transaction ID assigned by the bank.
* For OFX this is the <FITID>
* If a specific loader does not provide this, it is allowed to return
* null.
* @return Transaction ID
*/
public String getTrxID();
/**
* Additional reference information
* Statement line level reference information.
* For OFX this is the <REFNUM> field.
* If a specific loader does not provided this, it is allowed to return null.
* @return Error discription
*/
public String getReference();
/**
* Check number
* Check number, in case the transaction was initiated by a check.
* For OFX this is the <CHECKNUM> field, for MS-Money (OFC) this is the
* <CHKNUM> field.
* If a specific loader does not provide this, it is allowed to return null.
* @return Transaction reference
*/
public String getCheckNo();
/**
* Payee name
* Name information, for OFX this is the <NAME> or
* <PAYEE><NAME> field
* If a specific loader class does not provide this, it is allowed
* to return null.
* @return Payee name
*/
public String getPayeeName();
/**
* Payee account
* Account information of "the other party"
* If a specific loader class does not provide this, it is allowed
* to return null.
* @return Payee bank account number
*/
public String getPayeeAccountNo();
/**
* Statement line date
* This has to be provided by all loader classes.
* @return Statement line date
*/
public Timestamp getStatementLineDate();
/**
* Effective date
* Date theat the funds became available.
* If a specific loader does not provide this, it is allowed to return null.
* @return Effective date
*/
public Timestamp getValutaDate();
/**
* Transaction type
* @return Transaction type
* This returns the transaction type as used by the bank
* Whether a transaction is credit or debit depends on the amount (i.e. negative),
* this field is for reference only.
* If a specific loader class does not provide this, it is allowed
* to return null.
*/
public String getTrxType();
/**
* Indicates whether this transaction is a reversal
* @return true if this is a reversal
*/
public boolean getIsReversal();
/**
* Currency
* @return Currency
* Return the currency, if included in the statement data.
* It is returned as it appears in the import data, it should
* not be processed by the loader in any way.
* If a specific loader class does not provide this, it is allowed
* to return null.
*/
public String getCurrency();
/**
* Statement line amount
* @return Statement Line Amount
* This has to be provided by all loader classes.
*/
public BigDecimal getStmtAmt();
/**
* Transaction Amount
* @return Transaction Amount
*/
public BigDecimal getTrxAmt();
/**
* Interest Amount
* @return Interest Amount
*/
public BigDecimal getInterestAmt();
/**
* Transaction memo
* @return Memo
* Additional descriptive information.
* For OFX this is the <MEMO> filed, for SWIFT MT940
* this is the "86" line.
* If a specific loader does not provide this, it is allowed to return null.
*/
public String getMemo();
/**
* Charge name
* @return Charge name
* Name of the charge, in case this transaction is a bank charge.
* If a specific loader class does not provide this, it is allowed
* to return null.
*/
public String getChargeName();
/**
* Charge amount
* @return Charge amount
* Name of the charge, in case this transaction is a bank charge.
* If a specific loader class does not provide this, it is allowed
* to return null.
*/
public BigDecimal getChargeAmt();
} //BankStatementLoaderInterface

View File

@ -0,0 +1,103 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
/**
* Bank Statement Match Information.
* Returned by Bank Statement Matcher
*
* @author Jorg Janke
* @version $Id: BankStatementMatchInfo.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class BankStatementMatchInfo
{
/**
* Standard Constructor
*/
public BankStatementMatchInfo()
{
super();
} // BankStatementMatchInfo
private int m_C_BPartner_ID = 0;
private int m_C_Payment_ID = 0;
private int m_C_Invoice_ID = 0;
/**
* Do we have a match?
* @return true if something could be matched
*/
public boolean isMatched()
{
return m_C_BPartner_ID > 0 || m_C_Payment_ID > 0 || m_C_Invoice_ID > 0;
} // isValid
/**
* Get matched BPartner
* @return BPartner
*/
public int getC_BPartner_ID()
{
return m_C_BPartner_ID;
}
/**
* Set matched BPartner
* @param C_BPartner_ID BPartner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
m_C_BPartner_ID = C_BPartner_ID;
}
/**
* Get matched Payment
* @return Payment
*/
public int getC_Payment_ID()
{
return m_C_Payment_ID;
}
/**
* Set matched Payment
* @param C_Payment_ID payment
*/
public void setC_Payment_ID (int C_Payment_ID)
{
m_C_Payment_ID = C_Payment_ID;
}
/**
* Get matched Invoice
* @return invoice
*/
public int getC_Invoice_ID()
{
return m_C_Invoice_ID;
}
/**
* Set matched Invoice
* @param C_Invoice_ID invoice
*/
public void setC_Invoice_ID (int C_Invoice_ID)
{
m_C_Invoice_ID = C_Invoice_ID;
}
} // BankStatementMatchInfo

View File

@ -0,0 +1,45 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import org.compiere.model.*;
/**
* Bank Statement Matcher Algorithm Interface
*
* @author Jorg Janke
* @version $Id: BankStatementMatcherInterface.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public interface BankStatementMatcherInterface
{
/**
* Match Bank Statement Line
* @param bsl bank statement line
* @return found matches or null
*/
public BankStatementMatchInfo findMatch (MBankStatementLine bsl);
/**
* Match Bank Statement Import Line
* @param ibs bank statement import line
* @return found matches or null
*/
public BankStatementMatchInfo findMatch (X_I_BankStatement ibs);
} // BankStatementMatcherInterface

View File

@ -0,0 +1,89 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.math.*;
import java.util.logging.*;
import org.compiere.process.*;
/**
* Copy Import Format (lines)
*
* @author Jorg Janke
* @version $Id: CopyImportFormat.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class CopyImportFormat extends SvrProcess
{
private int from_AD_ImpFormat_ID = 0;
private int to_AD_ImpFormat_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_ImpFormat_ID"))
from_AD_ImpFormat_ID = ((BigDecimal)para[i].getParameter()).intValue();
else
log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name);
}
to_AD_ImpFormat_ID = getRecord_ID();
} // prepare
/**
* Process Copy
* @return info
* @throws Exception
*/
protected String doIt () throws Exception
{
log.info("doIt = From=" + from_AD_ImpFormat_ID + " To=" + to_AD_ImpFormat_ID);
MImpFormat from = new MImpFormat (getCtx(), from_AD_ImpFormat_ID, get_TrxName());
if (from.getAD_ImpFormat_ID() != from_AD_ImpFormat_ID)
throw new Exception ("From Format not found - " + from_AD_ImpFormat_ID);
//
MImpFormat to = new MImpFormat (getCtx(), to_AD_ImpFormat_ID, get_TrxName());
if (to.getAD_ImpFormat_ID() != to_AD_ImpFormat_ID)
throw new Exception ("To Format not found - " + from_AD_ImpFormat_ID);
//
if (from.getAD_Table_ID() != to.getAD_Table_ID())
throw new Exception ("From-To do Not have same Format Table");
//
MImpFormatRow[] rows = from.getRows(); // incl. inactive
for (int i = 0; i < rows.length; i++)
{
MImpFormatRow row = rows[i];
MImpFormatRow copy = new MImpFormatRow (to, row);
if (!copy.save())
throw new Exception ("Copy error");
}
String msg = "#" + rows.length;
if (!from.getFormatType().equals(to.getFormatType()))
return msg + " - Note: Format Type different!";
return msg;
} // doIt
} // CopyImportFormat

View File

@ -0,0 +1,600 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Import Format a Row
*
* @author Jorg Janke
* @version $Id: ImpFormat.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public final class ImpFormat
{
/**
* Format
* @param name name
* @param AD_Table_ID table
* @param formatType format type
*/
public ImpFormat (String name, int AD_Table_ID, String formatType)
{
setName(name);
setTable(AD_Table_ID);
setFormatType(formatType);
} // ImpFormat
/** Logger */
private static CLogger log = CLogger.getCLogger(ImpFormat.class);
private String m_name;
private String m_formatType;
/** The Table to be imported */
private int m_AD_Table_ID;
private String m_tableName;
private String m_tablePK;
private String m_tableUnique1;
private String m_tableUnique2;
private String m_tableUniqueParent;
private String m_tableUniqueChild;
//
private String m_BPartner;
private ArrayList<ImpFormatRow> m_rows = new ArrayList<ImpFormatRow>();
/**
* Set Name
* @param newName new name
*/
public void setName(String newName)
{
if (newName == null || newName.length() == 0)
throw new IllegalArgumentException("Name must be at least 1 char");
else
m_name = newName;
}
/**
* Get Name
* @return name
*/
public String getName()
{
return m_name;
} // getName
/**
* Import Table
* @param AD_Table_ID table
*/
public void setTable (int AD_Table_ID)
{
m_AD_Table_ID = AD_Table_ID;
m_tableName = null;
m_tablePK = null;
String sql = "SELECT t.TableName,c.ColumnName "
+ "FROM AD_Table t INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID AND c.IsKey='Y') "
+ "WHERE t.AD_Table_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Table_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_tableName = rs.getString(1);
m_tablePK = rs.getString(2);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "ImpFormat.setTable", e);
}
if (m_tableName == null || m_tablePK == null)
log.log(Level.SEVERE, "Data not found for AD_Table_ID=" + AD_Table_ID);
// Set Additional Table Info
m_tableUnique1 = "";
m_tableUnique2 = "";
m_tableUniqueParent = "";
m_tableUniqueChild = "";
if (m_AD_Table_ID == 311) // I_061_SyncItem
{
m_tableUnique1 = "H_UPC"; // UPC = unique
m_tableUnique2 = "Value";
m_tableUniqueChild = "H_Commodity1"; // Vendor No may not be unique !
m_tableUniqueParent = "H_PartnrID"; // Makes it unique
}
else if (m_AD_Table_ID == 532) // I_Product
{
m_tableUnique1 = "UPC"; // UPC = unique
m_tableUnique2 = "Value";
m_tableUniqueChild = "VendorProductNo"; // Vendor No may not be unique !
m_tableUniqueParent = "BPartner_Value"; // Makes it unique
}
else if (m_AD_Table_ID == 533) // I_BPartner
{
m_tableUnique1 = "Value"; // the key
}
else if (m_AD_Table_ID == 534) // I_ElementValue
{
m_tableUniqueParent = "ElementName"; // the parent key
m_tableUniqueChild = "Value"; // the key
}
else if (m_AD_Table_ID == 535) // I_ReportLine
{
m_tableUniqueParent = "ReportLineSetName"; // the parent key
m_tableUniqueChild = "Name"; // the key
}
} // setTable
/**
* Get Import Table Name
* @return AD_Table_ID
*/
public int getAD_Table_ID()
{
return m_AD_Table_ID;
} // getAD_Table_ID
/** Format Type - Fixed Length F */
public static final String FORMATTYPE_FIXED = "F";
/** Format Type - Comma Separated C */
public static final String FORMATTYPE_COMMA = "C";
/** Format Type - Tab Separated T */
public static final String FORMATTYPE_TAB = "T";
/** Format Type - XML X */
public static final String FORMATTYPE_XML = "X";
/**
* Set Format Type
* @param newFormatType - F/C/T/X
*/
public void setFormatType(String newFormatType)
{
if (newFormatType.equals(FORMATTYPE_FIXED) || newFormatType.equals(FORMATTYPE_COMMA)
|| newFormatType.equals(FORMATTYPE_TAB) || newFormatType.equals(FORMATTYPE_XML))
m_formatType = newFormatType;
else
throw new IllegalArgumentException("FormatType must be F/C/T/X");
} // setFormatType
/**
* Set Format Type
* @return format type - F/C/T/X
*/
public String getFormatType()
{
return m_formatType;
} // getFormatType
/**
* Set Business Partner
* @param newBPartner (value)
*/
public void setBPartner(String newBPartner)
{
m_BPartner = newBPartner;
} // setBPartner
/**
* Get Business Partner
* @return BPartner (value)
*/
public String getBPartner()
{
return m_BPartner;
} // getVPartner
/*************************************************************************
* Add Format Row
* @param row row
*/
public void addRow (ImpFormatRow row)
{
m_rows.add (row);
} // addRow
/**
* Get Row
* @param index index
* @return Import Format Row
*/
public ImpFormatRow getRow (int index)
{
if (index >=0 && index < m_rows.size())
return (ImpFormatRow)m_rows.get(index);
return null;
} // getRow
/**
* Get Row Count
* @return row count
*/
public int getRowCount()
{
return m_rows.size();
} // getRowCount
/*************************************************************************
* Factory load
* @param name name
* @return Import Format
*/
public static ImpFormat load (String name)
{
log.config(name);
ImpFormat retValue = null;
String sql = "SELECT * FROM AD_ImpFormat WHERE Name=?";
int ID = 0;
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setString (1, name);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
retValue = new ImpFormat (name, rs.getInt("AD_Table_ID"), rs.getString("FormatType"));
ID = rs.getInt ("AD_ImpFormat_ID");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return null;
}
loadRows (retValue, ID);
return retValue;
} // getFormat
/**
* Load Format Rows with ID
* @param format format
* @param ID id
*/
private static void loadRows (ImpFormat format, int ID)
{
String sql = "SELECT f.SeqNo,c.ColumnName,f.StartNo,f.EndNo,f.DataType,c.FieldLength," // 1..6
+ "f.DataFormat,f.DecimalPoint,f.DivideBy100,f.ConstantValue,f.Callout " // 7..11
+ "FROM AD_ImpFormat_Row f,AD_Column c "
+ "WHERE f.AD_ImpFormat_ID=? AND f.AD_Column_ID=c.AD_Column_ID AND f.IsActive='Y'"
+ "ORDER BY f.SeqNo";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt (1, ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
ImpFormatRow row = new ImpFormatRow (rs.getInt(1),
rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getString(5), rs.getInt(6));
//
row.setFormatInfo(rs.getString(7), rs.getString(8),
rs.getString(9).equals("Y"),
rs.getString(10), rs.getString(11));
//
format.addRow (row);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
} // loadLines
/*************************************************************************
* Parse Line returns ArrayList of values
*
* @param line line
* @param withLabel true if with label
* @param trace create trace info
* @param ignoreEmpty - ignore empty fields
* @return Array of values
*/
public String[] parseLine (String line, boolean withLabel, boolean trace, boolean ignoreEmpty)
{
if (trace)
log.config("" + line);
ArrayList<String> list = new ArrayList<String>();
// for all columns
for (int i = 0; i < m_rows.size(); i++)
{
ImpFormatRow row = (ImpFormatRow)m_rows.get(i);
StringBuffer entry = new StringBuffer ();
// Label-Start
if (withLabel)
{
entry.append(row.getColumnName());
entry.append("=");
if (row.isString())
entry.append("'");
else if (row.isDate())
entry.append("TO_DATE('");
}
// Get Data
String info = null;
if (row.isConstant())
info = "Constant";
else if (m_formatType.equals(FORMATTYPE_FIXED))
{
// check length
if (row.getStartNo() > 0 && row.getEndNo() <= line.length())
info = line.substring(row.getStartNo()-1, row.getEndNo());
}
else
{
info = parseFlexFormat (line, m_formatType, row.getStartNo());
}
if (info == null)
info = "";
// Interpret Data
entry.append(row.parse(info));
// Label-End
if (withLabel)
{
if (row.isString())
entry.append("'");
else if (row.isDate())
entry.append("','YYYY-MM-DD HH24:MI:SS')"); // JDBC Timestamp format w/o miliseconds
}
if (!ignoreEmpty || (ignoreEmpty && info.length() != 0))
list.add(entry.toString());
//
if (trace)
log.fine(info + "=>" + entry.toString() + " (Length=" + info.length() + ")");
} // for all columns
String[] retValue = new String[list.size()];
list.toArray(retValue);
return retValue;
} // parseLine
/**
* Parse flexible line format.
* A bit inefficient as it always starts from the start
*
* @param line the line to be parsed
* @param formatType Comma or Tab
* @param fieldNo number of field to be returned
* @return field in lime or ""
@throws IllegalArgumentException if format unknows
* */
private String parseFlexFormat (String line, String formatType, int fieldNo)
{
final char QUOTE = '"';
// check input
char delimiter = ' ';
if (formatType.equals(FORMATTYPE_COMMA))
delimiter = ',';
else if (formatType.equals(FORMATTYPE_TAB))
delimiter = '\t';
else
throw new IllegalArgumentException ("ImpFormat.parseFlexFormat - unknown format: " + formatType);
if (line == null || line.length() == 0 || fieldNo < 0)
return "";
// We need to read line sequentially as the fields may be delimited
// with quotes (") when fields contain the delimiter
// Example: "Artikel,bez","Artikel,""nr""",DEM,EUR
// needs to result in - Artikel,bez - Artikel,"nr" - DEM - EUR
int pos = 0;
int length = line.length();
for (int field = 1; field <= fieldNo && pos < length; field++)
{
StringBuffer content = new StringBuffer();
// two delimiter directly after each other
if (line.charAt(pos) == delimiter)
{
pos++;
continue;
}
// Handle quotes
if (line.charAt(pos) == QUOTE)
{
pos++; // move over beginning quote
while (pos < length)
{
// double quote
if (line.charAt(pos) == QUOTE && pos+1 < length && line.charAt(pos+1) == QUOTE)
{
content.append(line.charAt(pos++));
pos++;
}
// end quote
else if (line.charAt(pos) == QUOTE)
{
pos++;
break;
}
// normal character
else
content.append(line.charAt(pos++));
}
// we should be at end of line or a delimiter
if (pos < length && line.charAt(pos) != delimiter)
log.info("Did not find delimiter at pos " + pos + " " + line);
pos++; // move over delimiter
}
else // plain copy
{
while (pos < length && line.charAt(pos) != delimiter)
content.append(line.charAt(pos++));
pos++; // move over delimiter
}
if (field == fieldNo)
return content.toString();
}
// nothing found
return "";
} // parseFlexFormat
/*************************************************************************
* Insert/Update Database.
* @param ctx context
* @param line line
* @param trxName transaction
* @return true if inserted/updated
*/
public boolean updateDB (Properties ctx, String line, String trxName)
{
if (line == null || line.trim().length() == 0)
{
log.finest("No Line");
return false;
}
String[] nodes = parseLine (line, true, false, true); // with label, no trace, ignore empty
if (nodes.length == 0)
{
log.finest("Nothing parsed from: " + line);
return false;
}
// log.config( "ImpFormat.updateDB - listSize=" + nodes.length);
// Standard Fields
int AD_Client_ID = Env.getAD_Client_ID(ctx);
int AD_Org_ID = Env.getAD_Org_ID(ctx);
if (getAD_Table_ID() == X_I_GLJournal.Table_ID)
AD_Org_ID = 0;
int UpdatedBy = Env.getAD_User_ID(ctx);
// Check if the record is already there ------------------------------
StringBuffer sql = new StringBuffer ("SELECT COUNT(*), MAX(")
.append(m_tablePK).append(") FROM ").append(m_tableName)
.append(" WHERE AD_Client_ID=").append(AD_Client_ID).append(" AND (");
//
String where1 = null;
String where2 = null;
String whereParentChild = null;
for (int i = 0; i < nodes.length; i++)
{
if (nodes[i].endsWith("=''") || nodes[i].endsWith("=0"))
;
else if (nodes[i].startsWith(m_tableUnique1 + "="))
where1 = nodes[i];
else if (nodes[i].startsWith(m_tableUnique2 + "="))
where2 = nodes[i];
else if (nodes[i].startsWith(m_tableUniqueParent + "=") || nodes[i].startsWith(m_tableUniqueChild + "="))
{
if (whereParentChild == null)
whereParentChild = nodes[i];
else
whereParentChild += " AND " + nodes[i];
}
}
StringBuffer find = new StringBuffer();
if (where1 != null)
find.append(where1);
if (where2 != null)
{
if (find.length() > 0)
find.append(" OR ");
find.append(where2);
}
if (whereParentChild != null && whereParentChild.indexOf(" AND ") != -1) // need to have both criteria
{
if (find.length() > 0)
find.append(" OR (").append(whereParentChild).append(")"); // may have only one
else
find.append(whereParentChild);
}
sql.append(find).append(")");
int count = 0;
int ID = 0;
try
{
if (find.length() > 0)
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), trxName);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
count = rs.getInt(1);
if (count == 1)
ID = rs.getInt(2);
}
rs.close();
pstmt.close();
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
return false;
}
// Insert Basic Record -----------------------------------------------
if (ID == 0)
{
ID = DB.getNextID(ctx, m_tableName, null); // get ID
sql = new StringBuffer("INSERT INTO ")
.append(m_tableName).append("(").append(m_tablePK).append(",")
.append("AD_Client_ID,AD_Org_ID,Created,CreatedBy,Updated,UpdatedBy,IsActive") // StdFields
.append(") VALUES (").append(ID).append(",")
.append(AD_Client_ID).append(",").append(AD_Org_ID)
.append(",SysDate,").append(UpdatedBy).append(",SysDate,").append(UpdatedBy).append(",'Y'")
.append(")");
//
int no = DB.executeUpdate(sql.toString(), trxName);
if (no != 1)
{
log.log(Level.SEVERE, "Insert records=" + no + "; SQL=" + sql.toString());
return false;
}
log.finer("New ID=" + ID + " " + find);
}
else
log.finer("Old ID=" + ID + " " + find);
// Update Info -------------------------------------------------------
sql = new StringBuffer ("UPDATE ")
.append(m_tableName).append(" SET ");
for (int i = 0; i < nodes.length; i++)
sql.append(nodes[i]).append(","); // column=value
sql.append("IsActive='Y',Processed='N',I_IsImported='N',Updated=SysDate,UpdatedBy=").append(UpdatedBy);
sql.append(" WHERE ").append(m_tablePK).append("=").append(ID);
// Update Cmd
int no = DB.executeUpdate(sql.toString(), trxName);
if (no != 1)
{
log.log(Level.SEVERE, m_tablePK + "=" + ID + " - rows updated=" + no);
return false;
}
return true;
} // updateDB
} // ImpFormat

View File

@ -0,0 +1,490 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.math.*;
import java.sql.*;
import java.text.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Import Format Row with pasing capability
*
* @author Jorg Janke
* @version $Id: ImpFormatRow.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public final class ImpFormatRow
{
/**
* Constructor for fixed format
* @param seqNo sequence
* @param columnName db dolumn name
* @param startNo start no
* @param endNo and no
* @param dataType data type - see constants DATATYPE_
* @param maxLength if String it is the maximum length (truncated)
*/
public ImpFormatRow(int seqNo, String columnName, int startNo, int endNo, String dataType, int maxLength)
{
m_seqNo = seqNo;
setColumnName(columnName);
m_startNo = startNo;
m_endNo = endNo;
setDataType (dataType);
setMaxLength (maxLength);
} // ImpFormatRow
/**
* Constructor for non-fixed format
* @param seqNo sequence
* @param columnName db column name
* @param dataType data type - see constants DATATYPE_
* @param maxLength if String it is the maximum length (truncated)
*/
public ImpFormatRow(int seqNo, String columnName, String dataType, int maxLength)
{
m_seqNo = seqNo;
setColumnName(columnName);
setDataType (dataType);
setMaxLength (maxLength);
} // ImpFormatRow
private int m_seqNo;
private String m_columnName;
private int m_startNo = 0;
private int m_endNo = 0;
private String m_dataType;
private String m_dataFormat = "";
private String m_decimalPoint = ".";
private boolean m_divideBy100 = false;
private String m_constantValue = "";
private boolean m_constantIsString = true;
//
private Callout m_callout = null;
private String m_method = null;
//
private SimpleDateFormat m_dformat = null;
private int m_maxLength = 0;
/** Logger */
private CLogger log = CLogger.getCLogger(getClass());
/**
* Sequence No
* @return seq no
*/
public int getSeqNo ()
{
return m_seqNo;
} // getSeqNo
/**
* Set Sequence No
* @param newSeqNo sequence
*/
public void setSeqNo (int newSeqNo)
{
m_seqNo = newSeqNo;
} // setSeqNo
/**
* Start Position
* @param newStartNo start position
*/
public void setStartNo (int newStartNo)
{
m_startNo = newStartNo;
} // setStartNo
/**
* Get Start Position
* @return start position
*/
public int getStartNo()
{
return m_startNo;
} // getStartNo
/**
* End Position
* @param newEndNo end position
*/
public void setEndNo (int newEndNo)
{
m_endNo = newEndNo;
} // setEndNo
/**
* Get End Position
* @return End Position
*/
public int getEndNo ()
{
return m_endNo;
} // getEndNo
/**
* Column
* @param columnName column name
*/
public void setColumnName (String columnName)
{
if (columnName == null || columnName.length() == 0)
throw new IllegalArgumentException("ColumnName must be at least 1 char");
else
m_columnName = columnName;
} // setColumnName
/**
* Get Column Name
* @return Column Name
*/
public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Data Type
* @param dataType data type - see constants DATATYPE_
*/
public void setDataType (String dataType)
{
if (dataType.equals(DATATYPE_String) || dataType.equals(DATATYPE_Date)
|| dataType.equals(DATATYPE_Number) || dataType.equals(DATATYPE_Constant))
m_dataType = dataType;
else
throw new IllegalArgumentException("DataType must be S/D/N/C");
} // setDataType
/** String Data type */
public static final String DATATYPE_String = "S";
/** Data Data type */
public static final String DATATYPE_Date = "D";
/** Numeric Data type */
public static final String DATATYPE_Number = "N";
/** Constant Data type */
public static final String DATATYPE_Constant = "C";
/**
* Data Type
* @return data type
*/
public String getDataType()
{
return m_dataType;
} // getDataType
/**
* Is String
* @return true if data type is String
*/
public boolean isString()
{
if (m_dataType.equals(DATATYPE_Constant))
return m_constantIsString;
return m_dataType.equals(DATATYPE_String);
} // isString
/**
* Is Number
* @return true if data type is Number
*/
public boolean isNumber()
{
return m_dataType.equals(DATATYPE_Number);
}
/**
* Is Date
* @return true if data type is Date
*/
public boolean isDate()
{
return m_dataType.equals(DATATYPE_Date);
}
/**
* Is Constant
* @return true if data type is Constant
*/
public boolean isConstant()
{
return m_dataType.equals(DATATYPE_Constant);
}
/**
* Set Format Info
* @param dataFormat data format - see constants DATATYPE_
* @param decimalPoint decimal point representation
* @param divideBy100 divide number by 100
* @param constantValue constant value
* @param callout Java callout
*/
public void setFormatInfo (String dataFormat, String decimalPoint, boolean divideBy100,
String constantValue, String callout)
{
if (dataFormat == null)
m_dataFormat = "";
else
m_dataFormat = dataFormat;
// number
if (decimalPoint == null || !decimalPoint.equals(","))
m_decimalPoint = ".";
else
m_decimalPoint = ",";
m_divideBy100 = divideBy100;
// constant
if (constantValue == null || constantValue.length() == 0 || !m_dataType.equals(DATATYPE_Constant))
{
m_constantValue = "";
m_constantIsString = true;
}
else
{
m_constantValue = constantValue;
m_constantIsString = false;
for (int i = 0; i < m_constantValue.length(); i++)
{
char c = m_constantValue.charAt(i);
if (!(Character.isDigit(c) || c == '.')) // if a constant number, it must be with . (not ,)
{
m_constantIsString = true;
break;
}
}
}
// callout
if (callout != null)
{
int methodStart = callout.lastIndexOf(".");
try
{
if (methodStart != -1) // no class
{
Class cClass = Class.forName(callout.substring(0,methodStart));
m_callout = (Callout)cClass.newInstance();
m_method = callout.substring(methodStart+1);
}
}
catch (Exception e)
{
log.log(Level.SEVERE, "MTab.setFormatInfo - " + e.toString());
}
if (m_callout == null || m_method == null || m_method.length() == 0)
{
log.log(Level.SEVERE, "MTab.setFormatInfo - Invalid Callout " + callout);
m_callout = null;
}
}
} // setFormatInfo
/**
* Get Format
* @return Data Format
*/
public String getDataFormat()
{
return m_dataFormat;
}
/**
* Get Decimal Point
* @return Decimal Point
*/
public String getDecimalPoint()
{
return m_decimalPoint;
}
/**
* Divide result by 100
* @return true if result will be divided by 100
*/
public boolean isDivideBy100()
{
return m_divideBy100;
}
/**
* Get the constant value
* @return constant value
*/
public String getConstantValue()
{
return m_constantValue;
}
/**
* Set maximum length for Strings (truncated).
* Ignored, if 0
* @param maxLength max length
*/
public void setMaxLength (int maxLength)
{
m_maxLength = maxLength;
} // setMaxLength
/*************************************************************************
* Parse value.
* Field content in [] are treated as comments
* @param info data item
* @return pased info
*/
public String parse (String info)
{
if (info == null || info.length() == 0)
return "";
// Comment ?
if (info.startsWith("[") && info.endsWith("]"))
return "";
//
String retValue = null;
if (isNumber())
retValue = parseNumber (info);
else if (isDate())
retValue = parseDate (info);
else if (isConstant())
retValue = m_constantIsString ? parseString (m_constantValue) : m_constantValue;
else
retValue = parseString (info);
//
if (m_callout != null)
{
try
{
retValue = m_callout.convert (m_method, retValue);
}
catch (Exception e)
{
log.log(Level.SEVERE, "ImpFormatRow.parse - " + info + " (" + retValue + ")", e);
}
}
//
if (retValue == null)
retValue = "";
return retValue.trim();
} // parse
/**
* Return date as YYYY-MM-DD HH24:MI:SS (JDBC Timestamp format w/o miliseconds)
* @param info data
* @return date as JDBC format String
*/
private String parseDate (String info)
{
if (m_dformat == null)
{
try
{
m_dformat = new SimpleDateFormat(m_dataFormat);
}
catch (Exception e)
{
log.log(Level.SEVERE, "ImpFormatRow.parseDate Format=" + m_dataFormat, e);
}
if (m_dformat == null)
m_dformat = (SimpleDateFormat)DateFormat.getDateInstance();
m_dformat.setLenient(true);
}
Timestamp ts = null;
try
{
ts = new Timestamp (m_dformat.parse(info).getTime());
}
catch (ParseException pe)
{
log.log(Level.SEVERE, "ImpFormatRow.parseDate - " + info, pe);
}
if (ts == null)
ts = new Timestamp (System.currentTimeMillis());
//
String dateString = ts.toString();
return dateString.substring(0, dateString.indexOf(".")); // cut off miliseconds
} // parseNumber
/**
* Return String.
* - clean ' and backslash
* - check max length
* @param info data
* @return info with in SQL format
*/
private String parseString (String info)
{
String retValue = info;
// Length restriction
if (m_maxLength > 0 && retValue.length() > m_maxLength)
retValue = retValue.substring(0, m_maxLength);
// copy characters (wee need to look through anyway)
StringBuffer out = new StringBuffer(retValue.length());
for (int i = 0; i < retValue.length(); i++)
{
char c = retValue.charAt(i);
if (c == '\'')
out.append("''");
else if (c == '\\')
out.append("\\\\");
else
out.append(c);
}
return out.toString();
} // parseString
/**
* Return number with "." decimal
* @param info data
* @return converted number
*/
private String parseNumber (String info)
{
boolean hasPoint = info.indexOf(".") != -1;
boolean hasComma = info.indexOf(",") != -1;
// delete thousands
if (hasComma && m_decimalPoint.equals("."))
info = info.replace(',', ' ');
if (hasPoint && m_decimalPoint.equals(","))
info = info.replace('.', ' ');
hasComma = info.indexOf(",") != -1;
// replace decimal
if (hasComma && m_decimalPoint.equals(","))
info = info.replace(',', '.');
// remove everything but digits & '.'
char[] charArray = info.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < charArray.length; i++)
if (Character.isDigit(charArray[i]) || charArray[i] == '.')
sb.append(charArray[i]);
if (sb.length() == 0)
return "0";
BigDecimal bd = new BigDecimal(sb.toString());
if (m_divideBy100) // assumed two decimal scale
bd = bd.divide(new BigDecimal(100.0), 2, BigDecimal.ROUND_HALF_UP);
return bd.toString();
} // parseNumber
} // ImpFormatFow

View File

@ -0,0 +1,98 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Import Format Model
*
* @author Jorg Janke
* @version $Id: MImpFormat.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MImpFormat extends X_AD_ImpFormat
{
/**
* Standard Constructor
* @param ctx context
* @param AD_ImpFormat_ID id
* @param trxName transaction
*/
public MImpFormat (Properties ctx, int AD_ImpFormat_ID, String trxName)
{
super (ctx, AD_ImpFormat_ID, trxName);
} // MImpFormat
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MImpFormat (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MImpFormat
/**
* Get (all) Rows
* @return array of Rows
*/
public MImpFormatRow[] getRows()
{
ArrayList<MImpFormatRow> list = new ArrayList<MImpFormatRow>();
String sql = "SELECT * FROM AD_ImpFormat_Row "
+ "WHERE AD_ImpFormat_ID=? "
+ "ORDER BY SeqNo";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getAD_ImpFormat_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add(new MImpFormatRow (getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, "getRows", e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MImpFormatRow[] retValue = new MImpFormatRow[list.size ()];
list.toArray (retValue);
return retValue;
} // getRows
} // MImpFormat

View File

@ -0,0 +1,89 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.sql.*;
import java.util.*;
import org.compiere.model.*;
/**
* Import Format Row Model
*
* @author Jorg Janke
* @version $Id: MImpFormatRow.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MImpFormatRow extends X_AD_ImpFormat_Row
{
/**
* Standard Constructor
* @param ctx context
* @param AD_ImpFormat_Row_ID id
* @param trxName transaction
*/
public MImpFormatRow (Properties ctx, int AD_ImpFormat_Row_ID, String trxName)
{
super (ctx, AD_ImpFormat_Row_ID, trxName);
if (AD_ImpFormat_Row_ID == 0)
{
// setAD_ImpFormat_ID (0); Parent
// setAD_Column_ID (0);
// setDataType (null);
// setName (null);
// setSeqNo (10);
setDecimalPoint (".");
setDivideBy100 (false);
}
} // MImpFormatRow
/**
* Load Construcor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MImpFormatRow (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MImpFormatRow
/**
* Parent Construcor
* @param format format parent
*/
public MImpFormatRow (MImpFormat format)
{
this (format.getCtx(), 0, format.get_TrxName());
setAD_ImpFormat_ID(format.getAD_ImpFormat_ID());
} // MImpFormatRow
/**
* Parent/Copy Construcor
* @param parent format parent
* @param original to copy
*/
public MImpFormatRow (MImpFormat parent, MImpFormatRow original)
{
this (parent.getCtx(), 0, parent.get_TrxName());
copyValues(original, this);
setClientOrg(parent);
setAD_ImpFormat_ID(parent.getAD_ImpFormat_ID());
} // MImpFormatRow
} // MImpFormatRow

View File

@ -0,0 +1,242 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import java.io.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Covert OFX 1XX (SQGML) into valid XML
*
* SGML BASED OFX 1 compliant data is read from the BufferedReader
* passed to init. This class extends InputSream, allowing the
* XML compliant output data to be read from it.
*
* @author Maarten Klinker
* @version $Id: OFX1ToXML.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public final class OFX1ToXML extends InputStream implements Runnable
{
/** Reader object */
private PipedReader m_reader = new PipedReader();
/** Writer object */
private BufferedWriter m_writer;
/** Temp String */
private String m_ofx = "";
/** Logger */
private CLogger log = CLogger.getCLogger(getClass());
/**
* Constructor for OFX1ToXML
* @param is InputStream
* @throws IOException
*/
public OFX1ToXML(InputStream is) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
init(br);
} // OFX1ToXML
/**
* Constructor for OFX1ToXML
* @param br BufferedReader
* @throws IOException
*/
public OFX1ToXML(BufferedReader br) throws IOException
{
init(br);
} // OFX1ToXML
/**
* Method init
* @param br BufferedReader
* @throws IOException
*/
public void init(BufferedReader br) throws IOException
{
m_writer = new BufferedWriter(new PipedWriter(m_reader));
String line = br.readLine();
write("<?xml version=\"1.0\"?>\n");
write("<?OFX ");
while(line.indexOf("<") != 0)
{
if (line.length() > 0)
{
write(line.replaceAll(":", "=\"") + "\" ");
}
line = br.readLine();
}
write("?>\n");
while(line != null)
{
m_ofx += line + "\n";
line = br.readLine();
}
br.close();
new Thread(this).start();
} //i nit
/**
* Method run
* @see java.lang.Runnable#run()
*/
public void run()
{
boolean addCloseTag;
int tag2Start;
int tagStart;
int tagEnd;
String tag;
String line = "";
try
{
while(m_ofx != "")
{
addCloseTag = false;
tagStart = m_ofx.indexOf("<");
if (tagStart == -1)
{
break;
}
tagEnd = m_ofx.indexOf(">");
if (tagEnd <= tagStart + 1)
{
throw new IOException("PARSE ERROR: Invalid tag");
}
tag = m_ofx.substring(tagStart + 1, tagEnd);
if (tag.indexOf(" ") != -1)
{
throw new IOException("PARSE ERROR: Invalid tag");
}
if (!tag.startsWith("/"))
{
addCloseTag = (m_ofx.indexOf("</"+tag+">") == -1);
}
tag2Start = m_ofx.indexOf("<", tagEnd);
if (m_ofx.indexOf("\n", tagEnd) < tag2Start)
{
tag2Start = m_ofx.indexOf("\n", tagEnd);
}
if (tag2Start == -1)
{
tag2Start = m_ofx.length();
}
String data=m_ofx.substring(tagEnd+1, tag2Start);
line = m_ofx.substring(0, tagEnd+1)+xmlEncodeTextAsPCDATA(data);
m_ofx = m_ofx.substring(tag2Start);
if (addCloseTag)
{
line += "</" + tag + ">";
}
write(line);
}
write(m_ofx);
m_writer.close();
}
catch (IOException e)
{
log.log(Level.SEVERE, "Ofx1To2Convertor: IO Exception", e);
}
} // run
/**
* Method write
* @param str String
* @throws IOException
*/
private void write(String str) throws IOException
{
m_writer.write(str, 0, str.length());
} // write
/**
* Method read
* @return int
* @throws IOException
*/
public int read() throws IOException
{
return m_reader.read();
} // read
/**
* Method read
* @param cbuf char[]
* @param off int
* @param len int
* @return int
* @throws IOException
*/
public int read(char[] cbuf, int off, int len) throws IOException
{
return m_reader.read(cbuf, off, len);
} // read
/**
* Encodes strings for XML
* @param text text
* @return string
*/
public final static String xmlEncodeTextAsPCDATA(String text)
{
if (text == null)
return null;
char c;
StringBuffer n = new StringBuffer (text.length () * 2);
for (int i = 0; i < text.length (); i++)
{
c = text.charAt (i);
switch (c)
{
case '&':
n.append ("&amp;");
break;
case '<':
n.append ("&lt;");
break;
case '>':
n.append ("&gt;");
break;
case '"':
n.append ("&quot;");
break;
case '\'':
n.append ("&apos;");
break;
default:
{
n.append (c);
break;
}
}
}
return n.toString ();
} // xmlEncodeTextAsPCDATA
} //Ofx1To2Convertor

View File

@ -0,0 +1,817 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import org.compiere.model.*;
import org.compiere.util.Env;
import java.io.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
/**
* Parser for OFX bank statements
*
* This class is a parser for OFX bankstatements. OFX versions from 102 to 202
* and MS-Money OFC message sets are supported.
* Only fully XML compliant OFX data is supported. Files that are not XML
* compliant, e.g. OFX versions older then 200, will be preprocessed by
* the OFX1ToXML class before parsing.
* This class should be extended by a class that obtains the data to be parsed
* for example from a file, or using HTTP.
*
* @author Eldir Tomassen
* @version $Id: OFXBankStatementHandler.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public abstract class OFXBankStatementHandler extends DefaultHandler
{
protected MBankStatementLoader m_controller;
protected String m_errorMessage = "";
protected String m_errorDescription = "";
protected BufferedReader m_reader = null;
protected SAXParser m_parser;
protected boolean m_success = false;
//private boolean m_valid = false;
protected StatementLine m_line;
protected String m_routingNo = "0";
protected String m_bankAccountNo = null;
protected String m_currency = null;
protected int HEADER_SIZE = 20;
protected boolean m_test = false;
protected Timestamp m_dateLastRun = null;
protected Timestamp m_statementDate = null;
StringBuffer m_valueBuffer = new StringBuffer();
/** XML OFX Tag */
public static final String XML_OFX_TAG = "OFX";
/** XML SIGNONMSGSRSV2 Tag */
public static final String XML_SIGNONMSGSRSV2_TAG = "SIGNONMSGSRSV2";
/** XML SIGNONMSGSRSV1 Tag */
public static final String XML_SIGNONMSGSRSV1_TAG = "SIGNONMSGSRSV1";
/** Record-response aggregate */
public static final String XML_SONRS_TAG = "SONRS";
/** Date and time of the server response */
public static final String XML_DTSERVER_TAG = "DTSERVER";
/** Use USERKEY instead of USERID and USEPASS */
public static final String XML_USERKEY_TAG = "USERKEY";
/** Date and time that USERKEY expires */
public static final String XML_TSKEYEXPIRE_TAG = "TSKEYEXPIRE";
/** Language */
public static final String XML_LANGUAGE_TAG = "LANGUAGE";
/** Date and rime last update to profile information*/
public static final String XML_DTPROFUP_TAG = "DTPROFUP";
/** Status aggregate */
public static final String XML_STATUS_TAG = "STATUS";
/** Statement-response aggregate */
public static final String XML_STMTRS_TAG = "STMTRS";
/** XML CURDEF Tag */
public static final String XML_CURDEF_TAG = "CURDEF";
/** Account-from aggregate */
public static final String XML_BANKACCTFROM_TAG = "BANKACCTFROM";
/** Bank identifier */
public static final String XML_BANKID_TAG = "BANKID";
/** Branch identifier */
public static final String XML_BRANCHID_TAG = "BRANCHID";
/** XML ACCTID Tag */
public static final String XML_ACCTID_TAG = "ACCTID";
/** Type of account */
public static final String XML_ACCTTYPE_TAG = "ACCTTYPE";
/** Type of account */
public static final String XML_ACCTTYPE2_TAG = "ACCTTYPE2";
/** Checksum */
public static final String XML_ACCTKEY_TAG = "ACCTKEY";
/** XML BANKTRANLIST Tag */
public static final String XML_BANKTRANLIST_TAG = "BANKTRANLIST";
/** XML DTSTART Tag */
public static final String XML_DTSTART_TAG = "DTSTART";
/** XML DTEND Tag */
public static final String XML_DTEND_TAG = "DTEND";
/** XML STMTTRN Tag */
public static final String XML_STMTTRN_TAG = "STMTTRN";
/** XML TRNTYPE Tag */
public static final String XML_TRNTYPE_TAG = "TRNTYPE";
/** XML TRNAMT Tag */
public static final String XML_TRNAMT_TAG = "TRNAMT";
/** Transaction date */
public static final String XML_DTPOSTED_TAG = "DTPOSTED";
/** Effective date */
public static final String XML_DTAVAIL_TAG = "DTAVAIL";
/** XML FITID Tag */
public static final String XML_FITID_TAG = "FITID";
/** XML CHECKNUM Tag */
public static final String XML_CHECKNUM_TAG = "CHECKNUM";
/** XML CHKNUM Tag (MS-Money OFC) */
public static final String XML_CHKNUM_TAG = "CHKNUM";
/** XML REFNUM Tag */
public static final String XML_REFNUM_TAG = "REFNUM";
/** Transaction Memo */
public static final String XML_MEMO_TAG = "MEMO";
/** XML NAME Tag */
public static final String XML_NAME_TAG = "NAME";
/** XML PAYEEID Tag */
public static final String XML_PAYEEID_TAG = "PAYEEID";
/** TXML PAYEE Tag */
public static final String XML_PAYEE_TAG = "PAYEE";
/** XML LEDGERBAL Tag */
public static final String XML_LEDGERBAL_TAG = "LEDGERBAL";
/** XML BALAMT Tag */
public static final String XML_BALAMT_TAG = "BALAMT";
/** XML DTASOF Tag */
public static final String XML_DTASOF_TAG = "DTASOF";
/** XML AVAILBAL Tag */
public static final String XML_AVAILBAL_TAG = "AVAILBAL";
/** XML MKTGINFO Tag */
public static final String XML_MKTGINFO_TAG = "MKTGINFO";
/**
* Initialize the loader
* * @param controller Reference to the BankStatementLoaderController
@return Initialized succesfully
*/
protected boolean init(MBankStatementLoader controller)
{
boolean result = false;
if (controller == null)
{
m_errorMessage = "ErrorInitializingParser";
m_errorDescription = "ImportController is a null reference";
return result;
}
this.m_controller = controller;
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
m_parser = factory.newSAXParser();
result = true;
}
catch(ParserConfigurationException e)
{
m_errorMessage = "ErrorInitializingParser";
m_errorDescription = "Unable to configure SAX parser: " + e.getMessage();
}
catch(SAXException e)
{
m_errorMessage = "ErrorInitializingParser";
m_errorDescription = "Unable to initialize SAX parser: " + e.getMessage();
}
return result;
} // init
/**
* Attach OFX input source, detect whether we are dealing with OFX1
* (SGML) or OFX2 (XML). In case of OFX1, process the data to create
* valid XML.
* @param is Reference to the BankStatementLoaderController
* @return true if input is valid OFX data
*/
protected boolean attachInput(InputStream is)
{
boolean isOfx1 = true;
boolean result = false;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
reader.mark(HEADER_SIZE + 100);
String header = "";
for (int i = 0; i < HEADER_SIZE; i++)
{
header = header + reader.readLine();
}
if ((header.indexOf("<?OFX") != -1) || (header.indexOf("<?ofx") != -1))
{
isOfx1 = false;
}
else if ((header.indexOf("<?XML") != -1) || (header.indexOf("<?xml") != -1))
{
isOfx1 = false;
//deted specific OFX version
}
else
{
isOfx1 = true;
//detect specific OFX version
}
reader.reset();
if (isOfx1)
{
m_reader = new BufferedReader(new InputStreamReader(new OFX1ToXML(reader)));
}
else
{
m_reader = reader;
}
result = true;
}
catch(IOException e)
{
m_errorMessage = "ErrorReadingData";
m_errorDescription = e.getMessage();
return result;
}
return result;
} // attachInput
/** Verify the validity of the OFX data
* @return true if input is valid OFX data
*/
public boolean isValid()
{
boolean result = true;
/*
try
{
if (loadLines())
{
result = true;
test = false;
}
m_reader.reset();
}
catch(IOException e)
{
m_errorMessage = "ErrorReadingData";
m_errorDescription = e.getMessage();
}
*/
return result;
} //isValid
/** Check wether the import was succesfull
* @return true if all statement lines have been imported succesfully
*/
public boolean importSuccessfull()
{
/*
* Currently there are no checks after the statement lines are read.
* Once all lines are read correctly a successfull import is assumed.
*/
return m_success;
} // importSuccessfull
/**
* Read statementlines from InputStream.
* @return load success
* This method will be invoked from ImportController.
*/
public boolean loadLines()
{
boolean result = false;
try
{
m_parser.parse(new InputSource(m_reader), this);
result = true;
m_success = true;
}
catch(SAXException e)
{
m_errorMessage = "ErrorParsingData";
m_errorDescription = e.getMessage();
}
catch(IOException e)
{
m_errorMessage = "ErrorReadingData";
m_errorDescription = e.getMessage();
}
return result;
} // loadLines
/**
* Method getDateLastRun
* @return Timestamp
*/
public Timestamp getDateLastRun()
{
return m_dateLastRun;
}
/**
* Method getRoutingNo
* @return String
*/
public String getRoutingNo()
{
return m_line.routingNo;
}
/**
* Method getBankAccountNo
* @return String
*/
public String getBankAccountNo()
{
return m_line.bankAccountNo;
}
/**
* Method getStatementReference
* @return String
*/
public String getStatementReference()
{
return m_line.statementReference;
}
/**
* Method getStatementDate
* @return Timestamp
*/
public Timestamp getStatementDate()
{
return m_statementDate;
}
/**
* Method getReference
* @return String
*/
public String getReference()
{
return m_line.reference;
}
/**
* Method getStatementLineDate
* @return Timestamp
*/
public Timestamp getStatementLineDate()
{
return m_line.statementLineDate;
}
/**
* Method getValutaDate
* @return Timestamp
*/
public Timestamp getValutaDate()
{
return m_line.valutaDate;
}
/**
* Method getTrxType
* @return String
*/
public String getTrxType()
{
return m_line.trxType;
}
/**
* Method getIsReversal
* @return boolean
*/
public boolean getIsReversal()
{
return m_line.isReversal;
}
/**
* Method getCurrency
* @return String
*/
public String getCurrency()
{
return m_line.currency;
}
/**
* Method getStmtAmt
* @return BigDecimal
*/
public BigDecimal getStmtAmt()
{
return m_line.stmtAmt;
}
/**
* Method getTrxAmt
* @return Transaction Amount
*/
public BigDecimal getTrxAmt()
{
/* assume total amount = transaction amount
* todo: detect interest & charge amount
*/
return m_line.stmtAmt;
}
/**
* Method getInterestAmount
* @return Interest Amount
*/
public BigDecimal getInterestAmt()
{
return Env.ZERO;
}
/**
* Method getMemo
* @return String
*/
public String getMemo()
{
return m_line.memo;
}
/**
* Method getChargeName
* @return String
*/
public String getChargeName()
{
return m_line.chargeName;
}
/**
* Method getChargeAmt
* @return BigDecimal
*/
public BigDecimal getChargeAmt()
{
return m_line.chargeAmt;
}
/**
* Method getTrxID
* @return String
*/
public String getTrxID()
{
return m_line.trxID;
}
/**
* Method getPayeeAccountNo
* @return String
*/
public String getPayeeAccountNo()
{
return m_line.payeeAccountNo;
}
/**
* Method getPayeeName
* @return String
*/
public String getPayeeName()
{
return m_line.payeeName;
}
/**
* Method getCheckNo
* @return String
*/
public String getCheckNo()
{
return m_line.checkNo;
}
/**
* New XML element detected. The XML nesting
* structure is saved on the m_context stack.
* @param uri String
* @param localName String
* @param qName String
* @param attributes Attributes
* @throws org.xml.sax.SAXException
* @see org.xml.sax.ContentHandler#startElement(String, String, String, Attributes)
*/
public void startElement (String uri, String localName, String qName, Attributes attributes)
throws org.xml.sax.SAXException
{
boolean validOFX = true;
/*
* Currently no validating is being done, valid OFX structure is assumed.
*/
if (!validOFX)
{
m_errorDescription = "Invalid OFX syntax: " + qName;
throw new SAXException("Invalid OFX syntax: " + qName);
}
if (qName.equals(XML_STMTTRN_TAG))
{
m_line = new StatementLine(m_routingNo, m_bankAccountNo, m_currency);
}
m_valueBuffer=new StringBuffer();
} // startElement
/**
* Characters read from XML are assigned to a variable, based on the current m_context.
* No checks are being done, it is assumed that the context is correct.
* @param ch char[]
* @param start int
* @param length int
* @throws SAXException
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
**/
public void characters (char ch[], int start, int length) throws SAXException
{
m_valueBuffer.append(ch,start,length);
} // characters
/**
* Check for valid XML structure. (all tags are properly ended).
* The statements are passed to ImportController when the statement end (</STMTTRN>)
* is detected.
* @param uri String
* @param localName String
* @param qName String
* @throws SAXException
* @see org.xml.sax.ContentHandler#endElement(String, String, String)
*/
public void endElement (String uri, String localName, String qName) throws SAXException
{
String XML_TAG=qName;
String value=m_valueBuffer.toString();
try
{
//Read statment level data
/*
* Default currency for this set of statement lines
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>
*/
if (XML_TAG.equals(XML_CURDEF_TAG))
{
m_currency = value;
}
/* Routing Number (or SWIFT Code) for this set of statement lines
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKACCTFROM>
*/
else if (XML_TAG.equals(XML_BANKID_TAG))
{
m_routingNo = value;
}
/*
* Bank Account Number for this set of bank statement lines
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKACCTFROM>
*/
else if (XML_TAG.equals(XML_ACCTID_TAG))
{
m_bankAccountNo = value;
}
/*
* Last date for this set of statement lines
* This is the date that should be specified as the <DTSTART>
* for the next batch of statement lines, in order not to miss any
* transactions.
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST>
*/
else if (XML_TAG.equals(XML_DTEND_TAG))
{
m_dateLastRun = parseOfxDate(value);
}
/*
*
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<AVAILBAL>
*/
else if (XML_TAG.equals(XML_DTASOF_TAG))
{
m_statementDate = parseOfxDate(value);
}
//Read statement line level data
/*
* Transaction type, e.g. DEBIT, CREDIT, SRVCHG
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_TRNTYPE_TAG))
{
m_line.trxType = value;
}
/*
* Statement line date
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_DTPOSTED_TAG))
{
m_line.statementLineDate = parseOfxDate(value);
}
/*
* Valuta date
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_DTAVAIL_TAG))
{
m_line.valutaDate = parseOfxDate(value);
}
/*
* Total statement line amount
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_TRNAMT_TAG))
{
m_line.stmtAmt = new BigDecimal(value);
}
/*
* Transaction Identification
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_FITID_TAG))
{
m_line.trxID = value;
}
/*
* Check number for check transactions
* CHECKNUM for generic OFX, CHKNUM for MS-Money OFC
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if ((XML_TAG.equals(XML_CHECKNUM_TAG)) || (XML_TAG.equals(XML_CHKNUM_TAG)))
{
m_line.checkNo = value;
}
/*
* Statement line reference
* Additional transaction reference information
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_REFNUM_TAG))
{
m_line.reference = value;
}
/*
* Transaction memo
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_MEMO_TAG))
{
m_line.memo = value;
}
/*
* Payee Name
* <OFX>-<BANKMSGSRSV2>-<STMTTRNRS>-<STMTRS>-<BANKTRANLIST><STMTTRN>
*/
else if (XML_TAG.equals(XML_NAME_TAG))
{
m_line.payeeName = value;
}
}
catch(Exception e)
{
m_errorDescription = "Invalid data: " + value + " <-> " + e.getMessage();
throw new SAXException("Invalid data: " + value);
}
if (qName.equals(XML_STMTTRN_TAG))
{
if (!m_test)
{
if (!m_controller.saveLine())
{
m_errorMessage = m_controller.getErrorMessage();
m_errorDescription = m_controller.getErrorDescription();
throw new SAXException(m_errorMessage);
}
}
}
} // endElement
/**
* Method parseOfxDate
* @param value String
* @return Timestamp
* @throws ParseException
*/
private Timestamp parseOfxDate(String value) throws ParseException
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
return new Timestamp (sdf.parse(value).getTime());
}
catch(Exception e)
{
throw new ParseException("Error parsing date: " + value, 0);
}
} //parseOfxDate
/**
* Method getLastErrorMessage
* @return String
*/
public String getLastErrorMessage()
{
return m_errorMessage;
}
/**
* Method getLastErrorDescription
* @return String
*/
public String getLastErrorDescription()
{
return m_errorDescription;
}
/**
* @author ET
* @version $Id: OFXBankStatementHandler.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
class StatementLine
{
protected String routingNo = null;
protected String bankAccountNo = null;
protected String statementReference = null;
protected Timestamp statementLineDate = null;
protected String reference = null;
protected Timestamp valutaDate;
protected String trxType = null;
protected boolean isReversal = false;
protected String currency = null;
protected BigDecimal stmtAmt = null;
protected String memo = null;
protected String chargeName = null;
protected BigDecimal chargeAmt = null;
protected String payeeAccountNo = null;
protected String payeeName = null;
protected String trxID = null;
protected String checkNo = null;
/**
* Constructor for StatementLine
* @param RoutingNo String
* @param BankAccountNo String
* @param Currency String
*/
public StatementLine(String RoutingNo, String BankAccountNo, String Currency)
{
bankAccountNo = BankAccountNo;
routingNo = RoutingNo;
currency = Currency;
}
}
} //OFXBankStatementHandler

View File

@ -0,0 +1,100 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.impexp;
import org.compiere.model.*;
import java.io.*;
import org.xml.sax.SAXException;
/**
* Loader for OFX bank statements (file based)
*
* @author Eldir Tomassen
* @version $Id:
*/
public final class OFXFileBankStatementLoader extends OFXBankStatementHandler implements BankStatementLoaderInterface
{
/**
* Method init
* @param controller MBankStatementLoader
* @return boolean
* @see org.compiere.impexp.BankStatementLoaderInterface#init(MBankStatementLoader)
*/
public boolean init(MBankStatementLoader controller)
{
boolean result = false;
FileInputStream m_stream = null;
try
{
// Try to open the file specified as a process parameter
if (controller.getLocalFileName() != null)
{
m_stream = new FileInputStream(controller.getLocalFileName());
}
// Try to open the file specified as part of the loader configuration
else if (controller.getFileName() != null)
{
m_stream = new FileInputStream(controller.getFileName());
}
else
{
return result;
}
if (!super.init(controller))
{
return result;
}
if (m_stream == null)
{
return result;
}
result = attachInput(m_stream);
}
catch(Exception e)
{
m_errorMessage = "ErrorReadingData";
m_errorDescription = "";
}
return result;
} // init
/**
* Method characters
* @param ch char[]
* @param start int
* @param length int
* @throws SAXException
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
/*
* There are no additional things to do when importing from file.
* All data is handled by OFXBankStatementHandler
*/
super.characters(ch, start, length);
} // characterS
} // OFXFileBankStatementLoader

View File

@ -0,0 +1,34 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
$Id: package.html,v 1.1 2006/04/21 17:41:35 jjanke Exp $
Copyright 1999-2002 Jorg Janke, Inc.
40 Old Tannery Rd, Monroe, CT 06468, U.S.A.
All Rights Reserved.
-->
</head>
<body>
Provides for....
<h2>Package Specification</h2>
<ul>
<li><a href="http://www.adempiere.org">http://www.adempiere.org</a>
</ul>
<h2>Related Documentation</h2>
For overviews, tutorials, examples, guides, and tool documentation, please see:
<ul>
<li><a href="http://www.adempiere.org">http://www.adempiere.org</a>
</ul>
<!-- Put @see and @since tags down here. -->
</body>
</html>

View File

@ -0,0 +1,111 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Processor Interface
*
* @author Jorg Janke
* @version $Id: AdempiereProcessor.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/
public interface AdempiereProcessor
{
/**
* Get Client
* @return AD_Client_ID
*/
public int getAD_Client_ID();
/**
* Get Name
* @return Name
*/
public String getName();
/**
* Get Description
* @return Description
*/
public String getDescription();
/**
* Get Context
* @return context
*/
public Properties getCtx();
/**
* Get the frequency type
* @return frequency type
*/
public String getFrequencyType();
/**
* Get the frequency
* @return frequency
*/
public int getFrequency();
/**
* Get Unique ID
* @return Unique ID
*/
public String getServerID();
/**
* Get the date Next run
* @param requery requery database
* @return date next run
*/
public Timestamp getDateNextRun (boolean requery);
/**
* Set Date Next Run
* @param dateNextWork next work
*/
public void setDateNextRun(Timestamp dateNextWork);
/**
* Get the date Last run
* @return date lext run
*/
public Timestamp getDateLastRun ();
/**
* Set Date Last Run
* @param dateLastRun last run
*/
public void setDateLastRun(Timestamp dateLastRun);
/**
* Save
* @return true if saved
*/
public boolean save();
/**
* Get Processor Logs
* @return logs
*/
public AdempiereProcessorLog[] getLogs();
} // AdempiereProcessor

View File

@ -0,0 +1,65 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
/**
* Processor Log Interface
*
* @author Jorg Janke
* @version $Id: AdempiereProcessorLog.java,v 1.3 2006/07/30 00:51:04 jjanke Exp $
*/
public interface AdempiereProcessorLog
{
/**
* Get Created Date
* @return created
*/
public Timestamp getCreated();
/**
* Get Summary. Textual summary of this request
* @return Summary
*/
public String getSummary ();
/**
* Get Description. Optional short description of the record
* @return description
*/
public String getDescription ();
/**
* Get Error. An Error occured in the execution
* @return true if error
*/
public boolean isError ();
/**
* Get Reference. Reference for this record
* @return reference
*/
public String getReference ();
/**
* Get Text Message. Text Message
* @return text message
*/
public String getTextMsg ();
} // AdempiereProcessorLog

View File

@ -0,0 +1,60 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
/**
* Callout Interface for Callout.
* Used in MTab and ImpFormatRow
*
* @author Jorg Janke
* @version $Id: Callout.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public interface Callout
{
/**
* Start Callout.
* <p>
* Callout's are used for cross field validation and setting values in other fields
* when returning a non empty (error message) string, an exception is raised
* <p>
* When invoked, the Tab model has the new value!
*
* @param ctx Context
* @param method Method name
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @param oldValue The old value
* @return Error message or ""
*/
public String start (Properties ctx, String method, int WindowNo,
GridTab mTab, GridField mField, Object value, Object oldValue);
/**
* Conversion Rules.
* Convert a String
*
* @param method in notation User_Function
* @param value the value
* @return converted String or Null if no method found
*/
public String convert (String method, String value);
} // callout

View File

@ -0,0 +1,106 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Resource Assignment Callout
*
* @author Jorg Janke
* @version $Id: CalloutAssignment.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutAssignment extends CalloutEngine
{
/**
* Assignment_Product.
* - called from S_ResourceAssignment_ID
* - sets M_Product_ID, Description
* - Qty..
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
// get value
int S_ResourceAssignment_ID = ((Integer)value).intValue();
if (S_ResourceAssignment_ID == 0)
return "";
setCalloutActive(true);
int M_Product_ID = 0;
String Name = null;
String Description = null;
BigDecimal Qty = null;
String sql = "SELECT p.M_Product_ID, ra.Name, ra.Description, ra.Qty "
+ "FROM S_ResourceAssignment ra"
+ " INNER JOIN M_Product p ON (p.S_Resource_ID=ra.S_Resource_ID) "
+ "WHERE ra.S_ResourceAssignment_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, S_ResourceAssignment_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
M_Product_ID = rs.getInt (1);
Name = rs.getString(2);
Description = rs.getString(3);
Qty = rs.getBigDecimal(4);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "product", e);
}
log.fine("S_ResourceAssignment_ID=" + S_ResourceAssignment_ID + " - M_Product_ID=" + M_Product_ID);
if (M_Product_ID != 0)
{
mTab.setValue ("M_Product_ID", new Integer (M_Product_ID));
if (Description != null)
Name += " (" + Description + ")";
if (!".".equals(Name))
mTab.setValue("Description", Name);
//
String variable = "Qty"; // TimeExpenseLine
if (mTab.getTableName().startsWith("C_Order"))
variable = "QtyOrdered";
else if (mTab.getTableName().startsWith("C_Invoice"))
variable = "QtyInvoiced";
if (Qty != null)
mTab.setValue(variable, Qty);
}
setCalloutActive(false);
return "";
} // product
} // CalloutAssignment

View File

@ -0,0 +1,151 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Bank Statement Callout
*
* @author Jorg Janke
* @version $Id: CalloutBankStatement.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutBankStatement extends CalloutEngine
{
/**
* Bank Account Changed.
* Update Beginning Balance
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String bankAccount (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (value == null)
return "";
int C_BankAccount_ID = ((Integer)value).intValue();
MBankAccount ba = MBankAccount.get(ctx, C_BankAccount_ID);
mTab.setValue("BeginningBalance", ba.getCurrentBalance());
return "";
} // bankAccount
/**
* BankStmt - Amount.
* Calculate ChargeAmt = StmtAmt - TrxAmt - InterestAmt
* or id Charge is entered - InterestAmt = StmtAmt - TrxAmt - ChargeAmt
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String amount (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
setCalloutActive(true);
// Get Stmt & Trx
BigDecimal stmt = (BigDecimal)mTab.getValue("StmtAmt");
if (stmt == null)
stmt = Env.ZERO;
BigDecimal trx = (BigDecimal)mTab.getValue("TrxAmt");
if (trx == null)
trx = Env.ZERO;
BigDecimal bd = stmt.subtract(trx);
// Charge - calculate Interest
if (mField.getColumnName().equals("ChargeAmt"))
{
BigDecimal charge = (BigDecimal)value;
if (charge == null)
charge = Env.ZERO;
bd = bd.subtract(charge);
// log.trace(log.l5_DData, "Interest (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - Charge(" + charge + ")");
mTab.setValue("InterestAmt", bd);
}
// Calculate Charge
else
{
BigDecimal interest = (BigDecimal)mTab.getValue("InterestAmt");
if (interest == null)
interest = Env.ZERO;
bd = bd.subtract(interest);
// log.trace(log.l5_DData, "Charge (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - Interest(" + interest + ")");
mTab.setValue("ChargeAmt", bd);
}
setCalloutActive(false);
return "";
} // amount
/**
* BankStmt - Payment.
* Update Transaction Amount when payment is selected
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String payment (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Payment_ID = (Integer)value;
if (C_Payment_ID == null || C_Payment_ID.intValue() == 0)
return "";
//
BigDecimal stmt = (BigDecimal)mTab.getValue("StmtAmt");
if (stmt == null)
stmt = Env.ZERO;
String sql = "SELECT PayAmt FROM C_Payment_v WHERE C_Payment_ID=?"; // 1
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Payment_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
BigDecimal bd = rs.getBigDecimal(1);
mTab.setValue("TrxAmt", bd);
if (stmt.compareTo(Env.ZERO) == 0)
mTab.setValue("StmtAmt", bd);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "BankStmt_Payment", e);
return e.getLocalizedMessage();
}
// Recalculate Amounts
amount (ctx, WindowNo, mTab, mField, value);
return "";
} // payment
} // CalloutBankStatement

View File

@ -0,0 +1,150 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Cash Book Journal Callouts
*
* @author Jorg Janke
* @version $Id: CalloutCashJournal.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class CalloutCashJournal extends CalloutEngine
{
/**
* Cash Journal Line Invoice.
* when Invoice selected
* - set C_Currency, DiscountAnt, Amount, WriteOffAmt
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String invoice (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive()) // assuming it is resetting value
return "";
setCalloutActive(true);
Integer C_Invoice_ID = (Integer)value;
if (C_Invoice_ID == null || C_Invoice_ID.intValue() == 0)
{
mTab.setValue("C_Currency_ID", null);
setCalloutActive(false);
return "";
}
// Date
Timestamp ts = Env.getContextAsDate(ctx, WindowNo, "DateAcct"); // from C_Cash
if (ts == null)
ts = new Timestamp(System.currentTimeMillis());
//
String sql = "SELECT C_BPartner_ID, C_Currency_ID," // 1..2
+ "invoiceOpen(C_Invoice_ID, 0), IsSOTrx, " // 3..4
+ "paymentTermDiscount(invoiceOpen(C_Invoice_ID, 0),C_Currency_ID,C_PaymentTerm_ID,DateInvoiced,?) "
+ "FROM C_Invoice WHERE C_Invoice_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setTimestamp(1, ts);
pstmt.setInt(2, C_Invoice_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
mTab.setValue("C_Currency_ID", new Integer(rs.getInt(2)));
BigDecimal PayAmt = rs.getBigDecimal(3);
BigDecimal DiscountAmt = rs.getBigDecimal(5);
boolean isSOTrx = "Y".equals(rs.getString(4));
if (!isSOTrx)
{
PayAmt = PayAmt.negate();
DiscountAmt = DiscountAmt.negate();
}
//
mTab.setValue("Amount", PayAmt.subtract(DiscountAmt));
mTab.setValue("DiscountAmt", DiscountAmt);
mTab.setValue("WriteOffAmt", Env.ZERO);
Env.setContext(ctx, WindowNo, "InvTotalAmt", PayAmt.toString());
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "invoice", e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
setCalloutActive(false);
return "";
} // CashJournal_Invoice
/**
* Cash Journal Line Invoice Amounts.
* when DiscountAnt, Amount, WriteOffAmt change
* making sure that add up to InvTotalAmt (created by CashJournal_Invoice)
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String amounts (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
// Needs to be Invoice
if (isCalloutActive() || !"I".equals(mTab.getValue("CashType")))
return "";
// Check, if InvTotalAmt exists
String total = Env.getContext(ctx, WindowNo, "InvTotalAmt");
if (total == null || total.length() == 0)
return "";
BigDecimal InvTotalAmt = new BigDecimal(total);
setCalloutActive(true);
BigDecimal PayAmt = (BigDecimal)mTab.getValue("Amount");
BigDecimal DiscountAmt = (BigDecimal)mTab.getValue("DiscountAmt");
BigDecimal WriteOffAmt = (BigDecimal)mTab.getValue("WriteOffAmt");
String colName = mField.getColumnName();
log.fine(colName + " - Invoice=" + InvTotalAmt
+ " - Amount=" + PayAmt + ", Discount=" + DiscountAmt + ", WriteOff=" + WriteOffAmt);
// Amount - calculate write off
if (colName.equals("Amount"))
{
WriteOffAmt = InvTotalAmt.subtract(PayAmt).subtract(DiscountAmt);
mTab.setValue("WriteOffAmt", WriteOffAmt);
}
else // calculate PayAmt
{
PayAmt = InvTotalAmt.subtract(DiscountAmt).subtract(WriteOffAmt);
mTab.setValue("Amount", PayAmt);
}
setCalloutActive(false);
return "";
} // amounts
} // CalloutCashJournal

View File

@ -0,0 +1,242 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.lang.reflect.*;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Callout Emgine.
*
* @author Jorg Janke
* @version $Id: CalloutEngine.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutEngine implements Callout
{
/**
* Constructor
*/
public CalloutEngine()
{
super();
}
/** Logger */
protected CLogger log = CLogger.getCLogger(getClass());
/**
* Start Callout.
* <p>
* Callout's are used for cross field validation and setting values in other fields
* when returning a non empty (error message) string, an exception is raised
* <p>
* When invoked, the Tab model has the new value!
*
* @param ctx Context
* @param methodName Method name
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @param oldValue The old value
* @return Error message or ""
*/
public String start (Properties ctx, String methodName, int WindowNo,
GridTab mTab, GridField mField, Object value, Object oldValue)
{
if (methodName == null || methodName.length() == 0)
throw new IllegalArgumentException ("No Method Name");
//
String retValue = "";
StringBuffer msg = new StringBuffer(methodName).append(" - ")
.append(mField.getColumnName())
.append("=").append(value)
.append(" (old=").append(oldValue)
.append(") {active=").append(isCalloutActive()).append("}");
if (!isCalloutActive())
log.info (msg.toString());
// Find Method
Method method = getMethod(methodName);
if (method == null)
throw new IllegalArgumentException ("Method not found: " + methodName);
int argLength = method.getParameterTypes().length;
if (!(argLength == 5 || argLength == 6))
throw new IllegalArgumentException ("Method " + methodName
+ " has invalid no of arguments: " + argLength);
// Call Method
try
{
Object[] args = null;
if (argLength == 6)
args = new Object[] {ctx, new Integer(WindowNo), mTab, mField, value, oldValue};
else
args = new Object[] {ctx, new Integer(WindowNo), mTab, mField, value};
retValue = (String)method.invoke(this, args);
}
catch (Exception e)
{
setCalloutActive(false);
Throwable ex = e.getCause(); // InvocationTargetException
if (ex == null)
ex = e;
log.log(Level.SEVERE, "start: " + methodName, ex);
ex.printStackTrace(System.err);
retValue = ex.getLocalizedMessage();
}
return retValue;
} // start
/**
* Conversion Rules.
* Convert a String
*
* @param methodName method name
* @param value the value
* @return converted String or Null if no method found
*/
public String convert (String methodName, String value)
{
if (methodName == null || methodName.length() == 0)
throw new IllegalArgumentException ("No Method Name");
//
String retValue = null;
StringBuffer msg = new StringBuffer(methodName).append(" - ").append(value);
log.info (msg.toString());
//
// Find Method
Method method = getMethod(methodName);
if (method == null)
throw new IllegalArgumentException ("Method not found: " + methodName);
int argLength = method.getParameterTypes().length;
if (argLength != 1)
throw new IllegalArgumentException ("Method " + methodName
+ " has invalid no of arguments: " + argLength);
// Call Method
try
{
Object[] args = new Object[] {value};
retValue = (String)method.invoke(this, args);
}
catch (Exception e)
{
setCalloutActive(false);
log.log(Level.SEVERE, "convert: " + methodName, e);
e.printStackTrace(System.err);
}
return retValue;
} // convert
/**
* Get Method
* @param methodName method name
* @return method or null
*/
private Method getMethod (String methodName)
{
Method[] allMethods = getClass().getMethods();
for (int i = 0; i < allMethods.length; i++)
{
if (methodName.equals(allMethods[i].getName()))
return allMethods[i];
}
return null;
} // getMethod
/*************************************************************************/
private static boolean s_calloutActive = false;
/**
* Is Callout Active
* @return true if active
*/
protected static boolean isCalloutActive()
{
return s_calloutActive;
} // isCalloutActive
/**
* Set Callout (in)active
* @param active active
*/
protected static void setCalloutActive (boolean active)
{
s_calloutActive = active;
} // setCalloutActive
/**
* Set Account Date Value.
* org.compiere.model.CalloutEngine.dateAcct
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String dateAcct (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive()) // assuming it is resetting value
return "";
// setCalloutActive(true);
if (value == null || !(value instanceof Timestamp))
return "";
mTab.setValue("DateAcct", value);
// setCalloutActive(false);
return "";
} // dateAcct
/**
* Rate - set Multiply Rate from Divide Rate and vice versa
* org.compiere.model.CalloutEngine.rate
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String rate (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null) // assuming it is Conversion_Rate
return "";
setCalloutActive(true);
BigDecimal rate1 = (BigDecimal)value;
BigDecimal rate2 = Env.ZERO;
BigDecimal one = new BigDecimal(1.0);
if (rate1.doubleValue() != 0.0) // no divide by zero
rate2 = one.divide(rate1, 12, BigDecimal.ROUND_HALF_UP);
//
if (mField.getColumnName().equals("MultiplyRate"))
mTab.setValue("DivideRate", rate2);
else
mTab.setValue("MultiplyRate", rate2);
log.info(mField.getColumnName() + "=" + rate1 + " => " + rate2);
setCalloutActive(false);
return "";
} // rate
} // CalloutEngine

View File

@ -0,0 +1,227 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* GL Journal Callout
*
* @author Jorg Janke
* @version $Id: CalloutGLJournal.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutGLJournal extends CalloutEngine
{
/**
* Journal - Period.
* Check that selected period is in DateAcct Range or Adjusting Period
* Called when C_Period_ID or DateAcct, DateDoc changed
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String period (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
if (value == null || isCalloutActive())
return "";
setCalloutActive(true);
int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
Timestamp DateAcct = null;
if (colName.equals("DateAcct"))
DateAcct = (Timestamp)value;
else
DateAcct = (Timestamp)mTab.getValue("DateAcct");
int C_Period_ID = 0;
if (colName.equals("C_Period_ID"))
C_Period_ID = ((Integer)value).intValue();
// When DateDoc is changed, update DateAcct
if (colName.equals("DateDoc"))
{
mTab.setValue("DateAcct", value);
}
// When DateAcct is changed, set C_Period_ID
else if (colName.equals("DateAcct"))
{
String sql = "SELECT C_Period_ID "
+ "FROM C_Period "
+ "WHERE C_Year_ID IN "
+ " (SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID ="
+ " (SELECT C_Calendar_ID FROM AD_ClientInfo WHERE AD_Client_ID=?))"
+ " AND ? BETWEEN StartDate AND EndDate"
// globalqss - cruiz - Bug [ 1577712 ] Financial Period Bug
+ " AND IsActive='Y'"
+ " AND PeriodType='S'";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
pstmt.setTimestamp(2, DateAcct);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
C_Period_ID = rs.getInt(1);
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
if (C_Period_ID != 0)
mTab.setValue("C_Period_ID", new Integer(C_Period_ID));
}
// When C_Period_ID is changed, check if in DateAcct range and set to end date if not
else
{
String sql = "SELECT PeriodType, StartDate, EndDate "
+ "FROM C_Period WHERE C_Period_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Period_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String PeriodType = rs.getString(1);
Timestamp StartDate = rs.getTimestamp(2);
Timestamp EndDate = rs.getTimestamp(3);
if (PeriodType.equals("S")) // Standard Periods
{
// out of range - set to last day
if (DateAcct == null
|| DateAcct.before(StartDate) || DateAcct.after(EndDate))
mTab.setValue("DateAcct", EndDate);
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
}
setCalloutActive(false);
return "";
} // Journal_Period
/**
* Journal/Line - rate.
* Set CurrencyRate from DateAcct, C_ConversionType_ID, C_Currency_ID
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String rate (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (value == null)
return "";
// Source info
Integer Currency_ID = (Integer)mTab.getValue("C_Currency_ID");
int C_Currency_ID = Currency_ID.intValue();
Integer ConversionType_ID = (Integer)mTab.getValue("C_ConversionType_ID");
int C_ConversionType_ID = ConversionType_ID.intValue();
Timestamp DateAcct = (Timestamp)mTab.getValue("DateAcct");
if (DateAcct == null)
DateAcct = new Timestamp(System.currentTimeMillis());
//
int C_AcctSchema_ID = Env.getContextAsInt(ctx, WindowNo, "C_AcctSchema_ID");
MAcctSchema as = MAcctSchema.get (ctx, C_AcctSchema_ID);
int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
BigDecimal CurrencyRate = MConversionRate.getRate(C_Currency_ID, as.getC_Currency_ID(),
DateAcct, C_ConversionType_ID, AD_Client_ID, AD_Org_ID);
log.fine("rate = " + CurrencyRate);
if (CurrencyRate == null)
CurrencyRate = Env.ZERO;
mTab.setValue("CurrencyRate", CurrencyRate);
return "";
} // rate
/**
* JournalLine - Amt.
* Convert the source amount to accounted amount (AmtAcctDr/Cr)
* Called when source amount (AmtSourceCr/Dr) or rate changes
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String amt (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
if (value == null || isCalloutActive())
return "";
setCalloutActive(true);
// Get Target Currency & Precision from C_AcctSchema.C_Currency_ID
int C_AcctSchema_ID = Env.getContextAsInt(ctx, WindowNo, "C_AcctSchema_ID");
MAcctSchema as = MAcctSchema.get(ctx, C_AcctSchema_ID);
int Precision = as.getStdPrecision();
BigDecimal CurrencyRate = (BigDecimal)mTab.getValue("CurrencyRate");
if (CurrencyRate == null)
{
CurrencyRate = Env.ONE;
mTab.setValue("CurrencyRate", CurrencyRate);
}
// AmtAcct = AmtSource * CurrencyRate ==> Precision
BigDecimal AmtSourceDr = (BigDecimal)mTab.getValue("AmtSourceDr");
if (AmtSourceDr == null)
AmtSourceDr = Env.ZERO;
BigDecimal AmtSourceCr = (BigDecimal)mTab.getValue("AmtSourceCr");
if (AmtSourceCr == null)
AmtSourceCr = Env.ZERO;
BigDecimal AmtAcctDr = AmtSourceDr.multiply(CurrencyRate);
AmtAcctDr = AmtAcctDr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
mTab.setValue("AmtAcctDr", AmtAcctDr);
BigDecimal AmtAcctCr = AmtSourceCr.multiply(CurrencyRate);
AmtAcctCr = AmtAcctCr.setScale(Precision, BigDecimal.ROUND_HALF_UP);
mTab.setValue("AmtAcctCr", AmtAcctCr);
setCalloutActive(false);
return "";
} // amt
} // CalloutGLJournal

View File

@ -0,0 +1,521 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
import com.sun.org.apache.bcel.internal.generic.*;
/**
* Shipment/Receipt Callouts
*
* @author Jorg Janke
* @version $Id: CalloutInOut.java,v 1.7 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutInOut extends CalloutEngine
{
/**
* C_Order - Order Defaults.
* @param ctx
* @param WindowNo
* @param mTab
* @param mField
* @param value
* @return error message or ""
*/
public String order (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Order_ID = (Integer)value;
if (C_Order_ID == null || C_Order_ID.intValue() == 0)
return "";
// No Callout Active to fire dependent values
if (isCalloutActive()) // prevent recursive
return "";
// Get Details
MOrder order = new MOrder (ctx, C_Order_ID.intValue(), null);
if (order.get_ID() != 0)
{
mTab.setValue("DateOrdered", order.getDateOrdered());
mTab.setValue("POReference", order.getPOReference());
mTab.setValue("AD_Org_ID", new Integer(order.getAD_Org_ID()));
mTab.setValue("AD_OrgTrx_ID", new Integer(order.getAD_OrgTrx_ID()));
mTab.setValue("C_Activity_ID", new Integer(order.getC_Activity_ID()));
mTab.setValue("C_Campaign_ID", new Integer(order.getC_Campaign_ID()));
mTab.setValue("C_Project_ID", new Integer(order.getC_Project_ID()));
mTab.setValue("User1_ID", new Integer(order.getUser1_ID()));
mTab.setValue("User2_ID", new Integer(order.getUser2_ID()));
mTab.setValue("M_Warehouse_ID", new Integer(order.getM_Warehouse_ID()));
//
mTab.setValue("DeliveryRule", order.getDeliveryRule());
mTab.setValue("DeliveryViaRule", order.getDeliveryViaRule());
mTab.setValue("M_Shipper_ID", new Integer(order.getM_Shipper_ID()));
mTab.setValue("FreightCostRule", order.getFreightCostRule());
mTab.setValue("FreightAmt", order.getFreightAmt());
mTab.setValue("C_BPartner_ID", new Integer(order.getC_BPartner_ID()));
}
return "";
} // order
/**
* InOut - DocType.
* - sets MovementType
* - gets DocNo
* @param ctx
* @param WindowNo
* @param mTab
* @param mField
* @param value
* @return error message or ""
*/
public String docType (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_DocType_ID = (Integer)value;
if (C_DocType_ID == null || C_DocType_ID.intValue() == 0)
return "";
String sql = "SELECT d.DocBaseType, d.IsDocNoControlled, s.CurrentNext "
+ "FROM C_DocType d, AD_Sequence s "
+ "WHERE C_DocType_ID=?" // 1
+ " AND d.DocNoSequence_ID=s.AD_Sequence_ID(+)";
try
{
Env.setContext(ctx, WindowNo, "C_DocTypeTarget_ID", C_DocType_ID.intValue());
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_DocType_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Set Movement Type
String DocBaseType = rs.getString("DocBaseType");
if (DocBaseType.equals("MMS")) // Material Shipments
mTab.setValue("MovementType", "C-"); // Customer Shipments
else if (DocBaseType.equals("MMR")) // Material Receipts
mTab.setValue("MovementType", "V+"); // Vendor Receipts
// DocumentNo
if (rs.getString("IsDocNoControlled").equals("Y"))
mTab.setValue("DocumentNo", "<" + rs.getString("CurrentNext") + ">");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return e.getLocalizedMessage();
}
return "";
} // docType
/**
* M_InOut - Defaults for BPartner.
* - Location
* - Contact
* @param ctx
* @param WindowNo
* @param mTab
* @param mField
* @param value
* @return error message or ""
*/
public String bpartner (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_BPartner_ID = (Integer)value;
if (C_BPartner_ID == null || C_BPartner_ID.intValue() == 0)
return "";
String sql = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
+ "p.M_PriceList_ID,p.PaymentRule,p.POReference,"
+ "p.SO_Description,p.IsDiscountPrinted,"
+ "p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
+ "l.C_BPartner_Location_ID,c.AD_User_ID "
+ "FROM C_BPartner p, C_BPartner_Location l, AD_User c "
+ "WHERE p.C_BPartner_ID=l.C_BPartner_ID(+)"
+ " AND p.C_BPartner_ID=c.C_BPartner_ID(+)"
+ " AND p.C_BPartner_ID=?"; // 1
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID.intValue());
ResultSet rs = pstmt.executeQuery();
BigDecimal bd;
if (rs.next())
{
// Location
Integer ii = new Integer(rs.getInt("C_BPartner_Location_ID"));
if (rs.wasNull())
mTab.setValue("C_BPartner_Location_ID", null);
else
mTab.setValue("C_BPartner_Location_ID", ii);
// Contact
ii = new Integer(rs.getInt("AD_User_ID"));
if (rs.wasNull())
mTab.setValue("AD_User_ID", null);
else
mTab.setValue("AD_User_ID", ii);
// CreditAvailable
double CreditAvailable = rs.getDouble("CreditAvailable");
if (!rs.wasNull() && CreditAvailable < 0)
mTab.fireDataStatusEEvent("CreditLimitOver",
DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable),
false);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return e.getLocalizedMessage();
}
return "";
} // bpartner
/**
* M_Warehouse.
* Set Organization and Default Locator
* @param ctx
* @param WindowNo
* @param mTab
* @param mField
* @param value
* @return error message or ""
*/
public String warehouse (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
Integer M_Warehouse_ID = (Integer)value;
if (M_Warehouse_ID == null || M_Warehouse_ID.intValue() == 0)
return "";
setCalloutActive(true);
String sql = "SELECT w.AD_Org_ID, l.M_Locator_ID "
+ "FROM M_Warehouse w"
+ " LEFT OUTER JOIN M_Locator l ON (l.M_Warehouse_ID=w.M_Warehouse_ID AND l.IsDefault='Y') "
+ "WHERE w.M_Warehouse_ID=?"; // 1
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Warehouse_ID.intValue());
ResultSet rs = pstmt.executeQuery();
BigDecimal bd;
if (rs.next())
{
// Org
Integer ii = new Integer(rs.getInt(1));
int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
if (AD_Org_ID != ii.intValue())
mTab.setValue("AD_Org_ID", ii);
// Locator
ii = new Integer(rs.getInt(2));
if (rs.wasNull())
Env.setContext(ctx, WindowNo, 0, "M_Locator_ID", null);
else
{
log.config("M_Locator_ID=" + ii);
Env.setContext(ctx, WindowNo, "M_Locator_ID", ii.intValue());
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
setCalloutActive(false);
return "";
} // warehouse
/**************************************************************************
* OrderLine Callout
* @param ctx context
* @param WindowNo window no
* @param mTab tab model
* @param mField field model
* @param value new value
* @return error message or ""
*/
public String orderLine (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_OrderLine_ID = (Integer)value;
if (C_OrderLine_ID == null || C_OrderLine_ID.intValue() == 0)
return "";
setCalloutActive(true);
// Get Details
MOrderLine ol = new MOrderLine (ctx, C_OrderLine_ID.intValue(), null);
if (ol.get_ID() != 0)
{
mTab.setValue("M_Product_ID", new Integer(ol.getM_Product_ID()));
mTab.setValue("M_AttributeSetInstance_ID", new Integer(ol.getM_AttributeSetInstance_ID()));
//
mTab.setValue("C_UOM_ID", new Integer(ol.getC_UOM_ID()));
BigDecimal MovementQty = ol.getQtyOrdered().subtract(ol.getQtyDelivered());
mTab.setValue("MovementQty", MovementQty);
BigDecimal QtyEntered = MovementQty;
if (ol.getQtyEntered().compareTo(ol.getQtyOrdered()) != 0)
QtyEntered = QtyEntered.multiply(ol.getQtyEntered())
.divide(ol.getQtyOrdered(), 12, BigDecimal.ROUND_HALF_UP);
mTab.setValue("QtyEntered", QtyEntered);
//
mTab.setValue("C_Activity_ID", new Integer(ol.getC_Activity_ID()));
mTab.setValue("C_Campaign_ID", new Integer(ol.getC_Campaign_ID()));
mTab.setValue("C_Project_ID", new Integer(ol.getC_Project_ID()));
mTab.setValue("C_ProjectPhase_ID", new Integer(ol.getC_ProjectPhase_ID()));
mTab.setValue("C_ProjectTask_ID", new Integer(ol.getC_ProjectTask_ID()));
mTab.setValue("AD_OrgTrx_ID", new Integer(ol.getAD_OrgTrx_ID()));
mTab.setValue("User1_ID", new Integer(ol.getUser1_ID()));
mTab.setValue("User2_ID", new Integer(ol.getUser2_ID()));
}
setCalloutActive(false);
return "";
} // orderLine
/**
* M_InOutLine - Default UOM/Locator for Product.
* @param ctx context
* @param WindowNo window no
* @param mTab tab model
* @param mField field model
* @param value new value
* @return error message or ""
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
setCalloutActive(true);
// Set Attribute & Locator
int M_Locator_ID = 0;
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
{
mTab.setValue("M_AttributeSetInstance_ID",
new Integer(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
M_Locator_ID = Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Locator_ID");
if (M_Locator_ID != 0)
mTab.setValue("M_Locator_ID", new Integer(M_Locator_ID));
}
else
mTab.setValue("M_AttributeSetInstance_ID", null);
//
int M_Warehouse_ID = Env.getContextAsInt(ctx, WindowNo, "M_Warehouse_ID");
boolean IsSOTrx = "Y".equals(Env.getContext(ctx, WindowNo, "IsSOTrx"));
if (IsSOTrx)
{
setCalloutActive(false);
return "";
}
// Set UOM/Locator/Qty
MProduct product = MProduct.get(ctx, M_Product_ID.intValue());
mTab.setValue("C_UOM_ID", new Integer (product.getC_UOM_ID()));
BigDecimal QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
mTab.setValue("MovementQty", QtyEntered);
if (M_Locator_ID != 0)
; // already set
else if (product.getM_Locator_ID() != 0)
{
MLocator loc = MLocator.get(ctx, product.getM_Locator_ID());
if (M_Warehouse_ID == loc.getM_Warehouse_ID())
mTab.setValue("M_Locator_ID", new Integer (product.getM_Locator_ID()));
else
log.fine("No Locator for M_Product_ID=" + M_Product_ID + " and M_Warehouse_ID=" + M_Warehouse_ID);
}
else
log.fine("No Locator for M_Product_ID=" + M_Product_ID);
setCalloutActive(false);
return "";
} // product
/**
* InOut Line - Quantity.
* - called from C_UOM_ID, QtyEntered, MovementQty
* - enforces qty UOM relationship
* @param ctx context
* @param WindowNo window no
* @param mTab tab model
* @param mField field model
* @param value new value
* @return error message or ""
*/
public String qty (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID");
// log.log(Level.WARNING,"qty - init - M_Product_ID=" + M_Product_ID);
BigDecimal MovementQty, QtyEntered;
// No Product
if (M_Product_ID == 0)
{
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
mTab.setValue("MovementQty", QtyEntered);
}
// UOM Changed - convert from Entered -> Product
else if (mField.getColumnName().equals("C_UOM_ID"))
{
int C_UOM_To_ID = ((Integer)value).intValue();
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
BigDecimal QtyEntered1 = QtyEntered.setScale(MUOM.getPrecision(ctx, C_UOM_To_ID), BigDecimal.ROUND_HALF_UP);
if (QtyEntered.compareTo(QtyEntered1) != 0)
{
log.fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
+ "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
QtyEntered = QtyEntered1;
mTab.setValue("QtyEntered", QtyEntered);
}
MovementQty = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, QtyEntered);
if (MovementQty == null)
MovementQty = QtyEntered;
boolean conversion = QtyEntered.compareTo(MovementQty) != 0;
log.fine("UOM=" + C_UOM_To_ID
+ ", QtyEntered=" + QtyEntered
+ " -> " + conversion
+ " MovementQty=" + MovementQty);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("MovementQty", MovementQty);
}
// No UOM defined
else if (Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID") == 0)
{
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
mTab.setValue("MovementQty", QtyEntered);
}
// QtyEntered changed - calculate MovementQty
else if (mField.getColumnName().equals("QtyEntered"))
{
int C_UOM_To_ID = Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID");
QtyEntered = (BigDecimal)value;
BigDecimal QtyEntered1 = QtyEntered.setScale(MUOM.getPrecision(ctx, C_UOM_To_ID), BigDecimal.ROUND_HALF_UP);
if (QtyEntered.compareTo(QtyEntered1) != 0)
{
log.fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
+ "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
QtyEntered = QtyEntered1;
mTab.setValue("QtyEntered", QtyEntered);
}
MovementQty = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, QtyEntered);
if (MovementQty == null)
MovementQty = QtyEntered;
boolean conversion = QtyEntered.compareTo(MovementQty) != 0;
log.fine("UOM=" + C_UOM_To_ID
+ ", QtyEntered=" + QtyEntered
+ " -> " + conversion
+ " MovementQty=" + MovementQty);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("MovementQty", MovementQty);
}
// MovementQty changed - calculate QtyEntered (should not happen)
else if (mField.getColumnName().equals("MovementQty"))
{
int C_UOM_To_ID = Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID");
MovementQty = (BigDecimal)value;
int precision = MProduct.get(ctx, M_Product_ID).getUOMPrecision();
BigDecimal MovementQty1 = MovementQty.setScale(precision, BigDecimal.ROUND_HALF_UP);
if (MovementQty.compareTo(MovementQty1) != 0)
{
log.fine("Corrected MovementQty "
+ MovementQty + "->" + MovementQty1);
MovementQty = MovementQty1;
mTab.setValue("MovementQty", MovementQty);
}
QtyEntered = MUOMConversion.convertProductTo (ctx, M_Product_ID,
C_UOM_To_ID, MovementQty);
if (QtyEntered == null)
QtyEntered = MovementQty;
boolean conversion = MovementQty.compareTo(QtyEntered) != 0;
log.fine("UOM=" + C_UOM_To_ID
+ ", MovementQty=" + MovementQty
+ " -> " + conversion
+ " QtyEntered=" + QtyEntered);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("QtyEntered", QtyEntered);
}
//
setCalloutActive(false);
return "";
} // qty
/**
* M_InOutLine - ASI.
* @param ctx context
* @param WindowNo window no
* @param mTab tab model
* @param mField field model
* @param value new value
* @return error message or ""
*/
public String asi (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
Integer M_ASI_ID = (Integer)value;
if (M_ASI_ID == null || M_ASI_ID.intValue() == 0)
return "";
setCalloutActive(true);
//
int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID");
int M_Warehouse_ID = Env.getContextAsInt(ctx, WindowNo, "M_Warehouse_ID");
int M_Locator_ID = Env.getContextAsInt(ctx, WindowNo, "M_Locator_ID");
log.fine("M_Product_ID=" + M_Product_ID
+ ", M_ASI_ID=" + M_ASI_ID
+ " - M_Warehouse_ID=" + M_Warehouse_ID
+ ", M_Locator_ID=" + M_Locator_ID);
// Check Selection
int M_AttributeSetInstance_ID = Env.getContextAsInt(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID");
if (M_ASI_ID.intValue() == M_AttributeSetInstance_ID)
{
int selectedM_Locator_ID = Env.getContextAsInt(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_Locator_ID");
if (selectedM_Locator_ID != 0)
{
log.fine("Selected M_Locator_ID=" + selectedM_Locator_ID);
mTab.setValue("M_Locator_ID", new Integer (selectedM_Locator_ID));
}
}
setCalloutActive(false);
return "";
} // asi
} // CalloutInOut

View File

@ -0,0 +1,124 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Physical Inventory Callouts
*
* @author Jorg Janke
* @version $Id: CalloutInventory.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutInventory extends CalloutEngine
{
/**
* Product/Locator/ASI modified.
* Set Attribute Set Instance
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
Integer InventoryLine = (Integer)mTab.getValue("M_InventoryLine_ID");
if (InventoryLine != null && InventoryLine.intValue() != 0)
return "";
// New Line - Get Book Value
int M_Product_ID = 0;
Integer Product = (Integer)mTab.getValue("M_Product_ID");
if (Product != null)
M_Product_ID = Product.intValue();
if (M_Product_ID == 0)
return "";
int M_Locator_ID = 0;
Integer Locator = (Integer)mTab.getValue("M_Locator_ID");
if (Locator != null)
M_Locator_ID = Locator.intValue();
if (M_Locator_ID == 0)
return "";
setCalloutActive(true);
// Set Attribute
int M_AttributeSetInstance_ID = 0;
Integer ASI = (Integer)mTab.getValue("M_AttributeSetInstance_ID");
if (ASI != null)
M_AttributeSetInstance_ID = ASI.intValue();
// Product Selection
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID)
{
M_AttributeSetInstance_ID = Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID");
if (M_AttributeSetInstance_ID != 0)
mTab.setValue("M_AttributeSetInstance_ID", new Integer(M_AttributeSetInstance_ID));
else
mTab.setValue("M_AttributeSetInstance_ID", null);
}
// Set QtyBook from first storage location
BigDecimal bd = null;
String sql = "SELECT QtyOnHand FROM M_Storage "
+ "WHERE M_Product_ID=?" // 1
+ " AND M_Locator_ID=?" // 2
+ " AND M_AttributeSetInstance_ID=?";
if (M_AttributeSetInstance_ID == 0)
sql = "SELECT SUM(QtyOnHand) FROM M_Storage "
+ "WHERE M_Product_ID=?" // 1
+ " AND M_Locator_ID=?"; // 2
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
pstmt.setInt(2, M_Locator_ID);
if (M_AttributeSetInstance_ID != 0)
pstmt.setInt(3, M_AttributeSetInstance_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
bd = rs.getBigDecimal(1);
if (bd != null)
mTab.setValue("QtyBook", bd);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
//
log.info("M_Product_ID=" + M_Product_ID
+ ", M_Locator_ID=" + M_Locator_ID
+ ", M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID
+ " - QtyBook=" + bd);
setCalloutActive(false);
return "";
} // product
} // CalloutInventory

View File

@ -0,0 +1,764 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Invoice Callouts
*
* @author Jorg Janke
* @version $Id: CalloutInvoice.java,v 1.4 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutInvoice extends CalloutEngine
{
/**
* Invoice Header - DocType.
* - PaymentRule
* - temporary Document
* Context:
* - DocSubTypeSO
* - HasCharges
* - (re-sets Business Partner info of required)
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String docType (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_DocType_ID = (Integer)value;
if (C_DocType_ID == null || C_DocType_ID.intValue() == 0)
return "";
String sql = "SELECT d.HasCharges,'N',d.IsDocNoControlled,"
+ "s.CurrentNext, d.DocBaseType "
+ "FROM C_DocType d, AD_Sequence s "
+ "WHERE C_DocType_ID=?" // 1
+ " AND d.DocNoSequence_ID=s.AD_Sequence_ID(+)";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_DocType_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Charges - Set Context
Env.setContext(ctx, WindowNo, "HasCharges", rs.getString(1));
// DocumentNo
if (rs.getString(3).equals("Y"))
mTab.setValue("DocumentNo", "<" + rs.getString(4) + ">");
// DocBaseType - Set Context
String s = rs.getString(5);
Env.setContext(ctx, WindowNo, "DocBaseType", s);
// AP Check & AR Credit Memo
if (s.startsWith("AP"))
mTab.setValue("PaymentRule", "S"); // Check
else if (s.endsWith("C"))
mTab.setValue("PaymentRule", "P"); // OnCredit
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return e.getLocalizedMessage();
}
return "";
} // docType
/**
* Invoice Header- BPartner.
* - M_PriceList_ID (+ Context)
* - C_BPartner_Location_ID
* - AD_User_ID
* - POReference
* - SO_Description
* - IsDiscountPrinted
* - PaymentRule
* - C_PaymentTerm_ID
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String bPartner (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_BPartner_ID = (Integer)value;
if (C_BPartner_ID == null || C_BPartner_ID.intValue() == 0)
return "";
String sql = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
+ " COALESCE(p.M_PriceList_ID,g.M_PriceList_ID) AS M_PriceList_ID, p.PaymentRule,p.POReference,"
+ " p.SO_Description,p.IsDiscountPrinted,"
+ " p.SO_CreditLimit, p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
+ " l.C_BPartner_Location_ID,c.AD_User_ID,"
+ " COALESCE(p.PO_PriceList_ID,g.PO_PriceList_ID) AS PO_PriceList_ID, p.PaymentRulePO,p.PO_PaymentTerm_ID "
+ "FROM C_BPartner p"
+ " INNER JOIN C_BP_Group g ON (p.C_BP_Group_ID=g.C_BP_Group_ID)"
+ " LEFT OUTER JOIN C_BPartner_Location l ON (p.C_BPartner_ID=l.C_BPartner_ID AND l.IsBillTo='Y' AND l.IsActive='Y')"
+ " LEFT OUTER JOIN AD_User c ON (p.C_BPartner_ID=c.C_BPartner_ID) "
+ "WHERE p.C_BPartner_ID=? AND p.IsActive='Y'"; // #1
boolean IsSOTrx = Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID.intValue());
ResultSet rs = pstmt.executeQuery();
//
if (rs.next())
{
// PriceList & IsTaxIncluded & Currency
Integer ii = new Integer(rs.getInt(IsSOTrx ? "M_PriceList_ID" : "PO_PriceList_ID"));
if (!rs.wasNull())
mTab.setValue("M_PriceList_ID", ii);
else
{ // get default PriceList
int i = Env.getContextAsInt(ctx, "#M_PriceList_ID");
if (i != 0)
mTab.setValue("M_PriceList_ID", new Integer(i));
}
// PaymentRule
String s = rs.getString(IsSOTrx ? "PaymentRule" : "PaymentRulePO");
if (s != null && s.length() != 0)
{
if (Env.getContext(ctx, WindowNo, "DocBaseType").endsWith("C")) // Credits are Payment Term
s = "P";
else if (IsSOTrx && (s.equals("S") || s.equals("U"))) // No Check/Transfer for SO_Trx
s = "P"; // Payment Term
mTab.setValue("PaymentRule", s);
}
// Payment Term
ii = new Integer(rs.getInt(IsSOTrx ? "C_PaymentTerm_ID" : "PO_PaymentTerm_ID"));
if (!rs.wasNull())
mTab.setValue("C_PaymentTerm_ID", ii);
// Location
int locID = rs.getInt("C_BPartner_Location_ID");
// overwritten by InfoBP selection - works only if InfoWindow
// was used otherwise creates error (uses last value, may belong to differnt BP)
if (C_BPartner_ID.toString().equals(Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_ID")))
{
String loc = Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_Location_ID");
if (loc.length() > 0)
locID = Integer.parseInt(loc);
}
if (locID == 0)
mTab.setValue("C_BPartner_Location_ID", null);
else
mTab.setValue("C_BPartner_Location_ID", new Integer(locID));
// Contact - overwritten by InfoBP selection
int contID = rs.getInt("AD_User_ID");
if (C_BPartner_ID.toString().equals(Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_ID")))
{
String cont = Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "AD_User_ID");
if (cont.length() > 0)
contID = Integer.parseInt(cont);
}
if (contID == 0)
mTab.setValue("AD_User_ID", null);
else
mTab.setValue("AD_User_ID", new Integer(contID));
// CreditAvailable
if (IsSOTrx)
{
double CreditLimit = rs.getDouble("SO_CreditLimit");
if (CreditLimit != 0)
{
double CreditAvailable = rs.getDouble("CreditAvailable");
if (!rs.wasNull() && CreditAvailable < 0)
mTab.fireDataStatusEEvent("CreditLimitOver",
DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable),
false);
}
}
// PO Reference
s = rs.getString("POReference");
if (s != null && s.length() != 0)
mTab.setValue("POReference", s);
else
mTab.setValue("POReference", null);
// SO Description
s = rs.getString("SO_Description");
if (s != null && s.trim().length() != 0)
mTab.setValue("Description", s);
// IsDiscountPrinted
s = rs.getString("IsDiscountPrinted");
if (s != null && s.length() != 0)
mTab.setValue("IsDiscountPrinted", s);
else
mTab.setValue("IsDiscountPrinted", "N");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "bPartner", e);
return e.getLocalizedMessage();
}
return "";
} // bPartner
/**
* Set Payment Term.
* Payment Term has changed
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String paymentTerm (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_PaymentTerm_ID = (Integer)value;
int C_Invoice_ID = Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID");
if (C_PaymentTerm_ID == null || C_PaymentTerm_ID.intValue() == 0
|| C_Invoice_ID == 0) // not saved yet
return "";
//
MPaymentTerm pt = new MPaymentTerm (ctx, C_PaymentTerm_ID.intValue(), null);
if (pt.get_ID() == 0)
return "PaymentTerm not found";
boolean valid = pt.apply (C_Invoice_ID);
mTab.setValue("IsPayScheduleValid", valid ? "Y" : "N");
return "";
} // paymentTerm
/**************************************************************************
* Invoice Line - Product.
* - reset C_Charge_ID / M_AttributeSetInstance_ID
* - PriceList, PriceStd, PriceLimit, C_Currency_ID, EnforcePriceLimit
* - UOM
* Calls Tax
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
setCalloutActive(true);
mTab.setValue("C_Charge_ID", null);
// Set Attribute
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
mTab.setValue("M_AttributeSetInstance_ID", new Integer(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
else
mTab.setValue("M_AttributeSetInstance_ID", null);
/***** Price Calculation see also qty ****/
boolean IsSOTrx = Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y");
int C_BPartner_ID = Env.getContextAsInt(ctx, WindowNo, WindowNo, "C_BPartner_ID");
BigDecimal Qty = (BigDecimal)mTab.getValue("QtyInvoiced");
MProductPricing pp = new MProductPricing (M_Product_ID.intValue(), C_BPartner_ID, Qty, IsSOTrx);
//
int M_PriceList_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID");
pp.setM_PriceList_ID(M_PriceList_ID);
int M_PriceList_Version_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_Version_ID");
pp.setM_PriceList_Version_ID(M_PriceList_Version_ID);
Timestamp date = Env.getContextAsDate(ctx, WindowNo, "DateInvoiced");
pp.setPriceDate(date);
//
mTab.setValue("PriceList", pp.getPriceList());
mTab.setValue("PriceLimit", pp.getPriceLimit());
mTab.setValue("PriceActual", pp.getPriceStd());
mTab.setValue("PriceEntered", pp.getPriceStd());
mTab.setValue("C_Currency_ID", new Integer(pp.getC_Currency_ID()));
// mTab.setValue("Discount", pp.getDiscount());
mTab.setValue("C_UOM_ID", new Integer(pp.getC_UOM_ID()));
Env.setContext(ctx, WindowNo, "EnforcePriceLimit", pp.isEnforcePriceLimit() ? "Y" : "N");
Env.setContext(ctx, WindowNo, "DiscountSchema", pp.isDiscountSchema() ? "Y" : "N");
//
setCalloutActive(false);
return tax (ctx, WindowNo, mTab, mField, value);
} // product
/**
* Invoice Line - Charge.
* - updates PriceActual from Charge
* - sets PriceLimit, PriceList to zero
* Calles tax
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String charge (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Charge_ID = (Integer)value;
if (C_Charge_ID == null || C_Charge_ID.intValue() == 0)
return "";
// No Product defined
if (mTab.getValue("M_Product_ID") != null)
{
mTab.setValue("C_Charge_ID", null);
return "ChargeExclusively";
}
mTab.setValue("M_AttributeSetInstance_ID", null);
mTab.setValue("S_ResourceAssignment_ID", null);
mTab.setValue("C_UOM_ID", new Integer(100)); // EA
Env.setContext(ctx, WindowNo, "DiscountSchema", "N");
String sql = "SELECT ChargeAmt FROM C_Charge WHERE C_Charge_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Charge_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
mTab.setValue ("PriceEntered", rs.getBigDecimal (1));
mTab.setValue ("PriceActual", rs.getBigDecimal (1));
mTab.setValue ("PriceLimit", Env.ZERO);
mTab.setValue ("PriceList", Env.ZERO);
mTab.setValue ("Discount", Env.ZERO);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql + e);
return e.getLocalizedMessage();
}
//
return tax (ctx, WindowNo, mTab, mField, value);
} // charge
/**
* Invoice Line - Tax.
* - basis: Product, Charge, BPartner Location
* - sets C_Tax_ID
* Calles Amount
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String tax (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String column = mField.getColumnName();
if (value == null)
return "";
// Check Product
int M_Product_ID = 0;
if (column.equals("M_Product_ID"))
M_Product_ID = ((Integer)value).intValue();
else
M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID");
int C_Charge_ID = 0;
if (column.equals("C_Charge_ID"))
C_Charge_ID = ((Integer)value).intValue();
else
C_Charge_ID = Env.getContextAsInt(ctx, WindowNo, "C_Charge_ID");
log.fine("Product=" + M_Product_ID + ", C_Charge_ID=" + C_Charge_ID);
if (M_Product_ID == 0 && C_Charge_ID == 0)
return amt (ctx, WindowNo, mTab, mField, value); //
// Check Partner Location
int shipC_BPartner_Location_ID = Env.getContextAsInt(ctx, WindowNo, "C_BPartner_Location_ID");
if (shipC_BPartner_Location_ID == 0)
return amt (ctx, WindowNo, mTab, mField, value); //
log.fine("Ship BP_Location=" + shipC_BPartner_Location_ID);
int billC_BPartner_Location_ID = shipC_BPartner_Location_ID;
log.fine("Bill BP_Location=" + billC_BPartner_Location_ID);
// Dates
Timestamp billDate = Env.getContextAsDate(ctx, WindowNo, "DateInvoiced");
log.fine("Bill Date=" + billDate);
Timestamp shipDate = billDate;
log.fine("Ship Date=" + shipDate);
int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
log.fine("Org=" + AD_Org_ID);
int M_Warehouse_ID = Env.getContextAsInt(ctx, "#M_Warehouse_ID");
log.fine("Warehouse=" + M_Warehouse_ID);
//
int C_Tax_ID = Tax.get(ctx, M_Product_ID, C_Charge_ID, billDate, shipDate,
AD_Org_ID, M_Warehouse_ID, billC_BPartner_Location_ID, shipC_BPartner_Location_ID,
Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y"));
log.info("Tax ID=" + C_Tax_ID);
//
if (C_Tax_ID == 0)
mTab.fireDataStatusEEvent(CLogger.retrieveError());
else
mTab.setValue("C_Tax_ID", new Integer(C_Tax_ID));
//
return amt (ctx, WindowNo, mTab, mField, value);
} // tax
/**
* Invoice - Amount.
* - called from QtyInvoiced, PriceActual
* - calculates LineNetAmt
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String amt (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
// log.log(Level.WARNING,"amt - init");
int C_UOM_To_ID = Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID");
int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID");
int M_PriceList_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID");
int StdPrecision = MPriceList.getStandardPrecision(ctx, M_PriceList_ID);
BigDecimal QtyEntered, QtyInvoiced, PriceEntered, PriceActual, PriceLimit, Discount, PriceList;
// get values
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
QtyInvoiced = (BigDecimal)mTab.getValue("QtyInvoiced");
log.fine("QtyEntered=" + QtyEntered + ", Invoiced=" + QtyInvoiced + ", UOM=" + C_UOM_To_ID);
//
PriceEntered = (BigDecimal)mTab.getValue("PriceEntered");
PriceActual = (BigDecimal)mTab.getValue("PriceActual");
// Discount = (BigDecimal)mTab.getValue("Discount");
PriceLimit = (BigDecimal)mTab.getValue("PriceLimit");
PriceList = (BigDecimal)mTab.getValue("PriceList");
log.fine("PriceList=" + PriceList + ", Limit=" + PriceLimit + ", Precision=" + StdPrecision);
log.fine("PriceEntered=" + PriceEntered + ", Actual=" + PriceActual);// + ", Discount=" + Discount);
// Qty changed - recalc price
if ((mField.getColumnName().equals("QtyInvoiced")
|| mField.getColumnName().equals("QtyEntered")
|| mField.getColumnName().equals("M_Product_ID"))
&& !"N".equals(Env.getContext(ctx, WindowNo, "DiscountSchema")))
{
int C_BPartner_ID = Env.getContextAsInt(ctx, WindowNo, "C_BPartner_ID");
if (mField.getColumnName().equals("QtyEntered"))
QtyInvoiced = MUOMConversion.convertProductTo (ctx, M_Product_ID,
C_UOM_To_ID, QtyEntered);
if (QtyInvoiced == null)
QtyInvoiced = QtyEntered;
boolean IsSOTrx = Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y");
MProductPricing pp = new MProductPricing (M_Product_ID, C_BPartner_ID, QtyInvoiced, IsSOTrx);
pp.setM_PriceList_ID(M_PriceList_ID);
int M_PriceList_Version_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_Version_ID");
pp.setM_PriceList_Version_ID(M_PriceList_Version_ID);
Timestamp date = (Timestamp)mTab.getValue("DateInvoiced");
pp.setPriceDate(date);
//
PriceEntered = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, pp.getPriceStd());
if (PriceEntered == null)
PriceEntered = pp.getPriceStd();
//
log.fine("amt - QtyChanged -> PriceActual=" + pp.getPriceStd()
+ ", PriceEntered=" + PriceEntered + ", Discount=" + pp.getDiscount());
mTab.setValue("PriceActual", pp.getPriceStd());
// mTab.setValue("Discount", pp.getDiscount());
mTab.setValue("PriceEntered", PriceEntered);
Env.setContext(ctx, WindowNo, "DiscountSchema", pp.isDiscountSchema() ? "Y" : "N");
}
else if (mField.getColumnName().equals("PriceActual"))
{
PriceActual = (BigDecimal)value;
PriceEntered = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, PriceActual);
if (PriceEntered == null)
PriceEntered = PriceActual;
//
log.fine("amt - PriceActual=" + PriceActual
+ " -> PriceEntered=" + PriceEntered);
mTab.setValue("PriceEntered", PriceEntered);
}
else if (mField.getColumnName().equals("PriceEntered"))
{
PriceEntered = (BigDecimal)value;
PriceActual = MUOMConversion.convertProductTo (ctx, M_Product_ID,
C_UOM_To_ID, PriceEntered);
if (PriceActual == null)
PriceActual = PriceEntered;
//
log.fine("amt - PriceEntered=" + PriceEntered
+ " -> PriceActual=" + PriceActual);
mTab.setValue("PriceActual", PriceActual);
}
/** Discount entered - Calculate Actual/Entered
if (mField.getColumnName().equals("Discount"))
{
PriceActual = new BigDecimal ((100.0 - Discount.doubleValue()) / 100.0 * PriceList.doubleValue());
if (PriceActual.scale() > StdPrecision)
PriceActual = PriceActual.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
PriceEntered = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, PriceActual);
if (PriceEntered == null)
PriceEntered = PriceActual;
mTab.setValue("PriceActual", PriceActual);
mTab.setValue("PriceEntered", PriceEntered);
}
// calculate Discount
else
{
if (PriceList.intValue() == 0)
Discount = Env.ZERO;
else
Discount = new BigDecimal ((PriceList.doubleValue() - PriceActual.doubleValue()) / PriceList.doubleValue() * 100.0);
if (Discount.scale() > 2)
Discount = Discount.setScale(2, BigDecimal.ROUND_HALF_UP);
mTab.setValue("Discount", Discount);
}
log.fine("amt = PriceEntered=" + PriceEntered + ", Actual" + PriceActual + ", Discount=" + Discount);
/* */
// Check PriceLimit
String epl = Env.getContext(ctx, WindowNo, "EnforcePriceLimit");
boolean enforce = Env.isSOTrx(ctx, WindowNo) && epl != null && epl.equals("Y");
if (enforce && MRole.getDefault().isOverwritePriceLimit())
enforce = false;
// Check Price Limit?
if (enforce && PriceLimit.doubleValue() != 0.0
&& PriceActual.compareTo(PriceLimit) < 0)
{
PriceActual = PriceLimit;
PriceEntered = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, PriceLimit);
if (PriceEntered == null)
PriceEntered = PriceLimit;
log.fine("amt =(under) PriceEntered=" + PriceEntered + ", Actual" + PriceLimit);
mTab.setValue ("PriceActual", PriceLimit);
mTab.setValue ("PriceEntered", PriceEntered);
mTab.fireDataStatusEEvent ("UnderLimitPrice", "", false);
// Repeat Discount calc
if (PriceList.intValue() != 0)
{
Discount = new BigDecimal ((PriceList.doubleValue () - PriceActual.doubleValue ()) / PriceList.doubleValue () * 100.0);
if (Discount.scale () > 2)
Discount = Discount.setScale (2, BigDecimal.ROUND_HALF_UP);
// mTab.setValue ("Discount", Discount);
}
}
// Line Net Amt
BigDecimal LineNetAmt = QtyInvoiced.multiply(PriceActual);
if (LineNetAmt.scale() > StdPrecision)
LineNetAmt = LineNetAmt.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
log.info("amt = LineNetAmt=" + LineNetAmt);
mTab.setValue("LineNetAmt", LineNetAmt);
// Calculate Tax Amount for PO
boolean IsSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx"));
if (!IsSOTrx)
{
BigDecimal TaxAmt = null;
if (mField.getColumnName().equals("TaxAmt"))
{
TaxAmt = (BigDecimal)mTab.getValue("TaxAmt");
}
else
{
Integer taxID = (Integer)mTab.getValue("C_Tax_ID");
if (taxID != null)
{
int C_Tax_ID = taxID.intValue();
MTax tax = new MTax (ctx, C_Tax_ID, null);
TaxAmt = tax.calculateTax(LineNetAmt, isTaxIncluded(WindowNo), StdPrecision);
mTab.setValue("TaxAmt", TaxAmt);
}
}
// Add it up
mTab.setValue("LineTotalAmt", LineNetAmt.add(TaxAmt));
}
setCalloutActive(false);
return "";
} // amt
/**
* Is Tax Included
* @param WindowNo window no
* @return tax included (default: false)
*/
private boolean isTaxIncluded (int WindowNo)
{
String ss = Env.getContext(Env.getCtx(), WindowNo, "IsTaxIncluded");
// Not Set Yet
if (ss.length() == 0)
{
int M_PriceList_ID = Env.getContextAsInt(Env.getCtx(), WindowNo, "M_PriceList_ID");
if (M_PriceList_ID == 0)
return false;
ss = DB.getSQLValueString(null,
"SELECT IsTaxIncluded FROM M_PriceList WHERE M_PriceList_ID=?",
M_PriceList_ID);
if (ss == null)
ss = "N";
Env.setContext(Env.getCtx(), WindowNo, "IsTaxIncluded", ss);
}
return "Y".equals(ss);
} // isTaxIncluded
/**
* Invoice Line - Quantity.
* - called from C_UOM_ID, QtyEntered, QtyInvoiced
* - enforces qty UOM relationship
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String qty (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, "M_Product_ID");
// log.log(Level.WARNING,"qty - init - M_Product_ID=" + M_Product_ID);
BigDecimal QtyInvoiced, QtyEntered, PriceActual, PriceEntered;
// No Product
if (M_Product_ID == 0)
{
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
mTab.setValue("QtyInvoiced", QtyEntered);
}
// UOM Changed - convert from Entered -> Product
else if (mField.getColumnName().equals("C_UOM_ID"))
{
int C_UOM_To_ID = ((Integer)value).intValue();
QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
BigDecimal QtyEntered1 = QtyEntered.setScale(MUOM.getPrecision(ctx, C_UOM_To_ID), BigDecimal.ROUND_HALF_UP);
if (QtyEntered.compareTo(QtyEntered1) != 0)
{
log.fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
+ "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
QtyEntered = QtyEntered1;
mTab.setValue("QtyEntered", QtyEntered);
}
QtyInvoiced = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, QtyEntered);
if (QtyInvoiced == null)
QtyInvoiced = QtyEntered;
boolean conversion = QtyEntered.compareTo(QtyInvoiced) != 0;
PriceActual = (BigDecimal)mTab.getValue("PriceActual");
PriceEntered = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, PriceActual);
if (PriceEntered == null)
PriceEntered = PriceActual;
log.fine("qty - UOM=" + C_UOM_To_ID
+ ", QtyEntered/PriceActual=" + QtyEntered + "/" + PriceActual
+ " -> " + conversion
+ " QtyInvoiced/PriceEntered=" + QtyInvoiced + "/" + PriceEntered);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("QtyInvoiced", QtyInvoiced);
mTab.setValue("PriceEntered", PriceEntered);
}
// QtyEntered changed - calculate QtyInvoiced
else if (mField.getColumnName().equals("QtyEntered"))
{
int C_UOM_To_ID = Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID");
QtyEntered = (BigDecimal)value;
BigDecimal QtyEntered1 = QtyEntered.setScale(MUOM.getPrecision(ctx, C_UOM_To_ID), BigDecimal.ROUND_HALF_UP);
if (QtyEntered.compareTo(QtyEntered1) != 0)
{
log.fine("Corrected QtyEntered Scale UOM=" + C_UOM_To_ID
+ "; QtyEntered=" + QtyEntered + "->" + QtyEntered1);
QtyEntered = QtyEntered1;
mTab.setValue("QtyEntered", QtyEntered);
}
QtyInvoiced = MUOMConversion.convertProductFrom (ctx, M_Product_ID,
C_UOM_To_ID, QtyEntered);
if (QtyInvoiced == null)
QtyInvoiced = QtyEntered;
boolean conversion = QtyEntered.compareTo(QtyInvoiced) != 0;
log.fine("qty - UOM=" + C_UOM_To_ID
+ ", QtyEntered=" + QtyEntered
+ " -> " + conversion
+ " QtyInvoiced=" + QtyInvoiced);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("QtyInvoiced", QtyInvoiced);
}
// QtyInvoiced changed - calculate QtyEntered (should not happen)
else if (mField.getColumnName().equals("QtyInvoiced"))
{
int C_UOM_To_ID = Env.getContextAsInt(ctx, WindowNo, "C_UOM_ID");
QtyInvoiced = (BigDecimal)value;
int precision = MProduct.get(ctx, M_Product_ID).getUOMPrecision();
BigDecimal QtyInvoiced1 = QtyInvoiced.setScale(precision, BigDecimal.ROUND_HALF_UP);
if (QtyInvoiced.compareTo(QtyInvoiced1) != 0)
{
log.fine("Corrected QtyInvoiced Scale "
+ QtyInvoiced + "->" + QtyInvoiced1);
QtyInvoiced = QtyInvoiced1;
mTab.setValue("QtyInvoiced", QtyInvoiced);
}
QtyEntered = MUOMConversion.convertProductTo (ctx, M_Product_ID,
C_UOM_To_ID, QtyInvoiced);
if (QtyEntered == null)
QtyEntered = QtyInvoiced;
boolean conversion = QtyInvoiced.compareTo(QtyEntered) != 0;
log.fine("qty - UOM=" + C_UOM_To_ID
+ ", QtyInvoiced=" + QtyInvoiced
+ " -> " + conversion
+ " QtyEntered=" + QtyEntered);
Env.setContext(ctx, WindowNo, "UOMConversion", conversion ? "Y" : "N");
mTab.setValue("QtyEntered", QtyEntered);
}
//
setCalloutActive(false);
return "";
} // qty
} // CalloutInvoice

View File

@ -0,0 +1,393 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Callouts for Invoice Batch
*
* @author Jorg Janke
* @version $Id: CalloutInvoiceBatch.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutInvoiceBatch extends CalloutEngine
{
/**
* Invoice Batch Line - DateInvoiced.
* - updates DateAcct
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String date (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (value == null)
return "";
mTab.setValue ("DateAcct", value);
//
setDocumentNo(ctx, WindowNo, mTab);
return "";
} // date
/**
* Invoice Batch Line - BPartner.
* - C_BPartner_Location_ID
* - AD_User_ID
* - PaymentRule
* - C_PaymentTerm_ID
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String bPartner (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_BPartner_ID = (Integer)value;
if (C_BPartner_ID == null || C_BPartner_ID.intValue() == 0)
return "";
String sql = "SELECT p.AD_Language,p.C_PaymentTerm_ID,"
+ " COALESCE(p.M_PriceList_ID,g.M_PriceList_ID) AS M_PriceList_ID, p.PaymentRule,p.POReference,"
+ " p.SO_Description,p.IsDiscountPrinted,"
+ " p.SO_CreditLimit, p.SO_CreditLimit-p.SO_CreditUsed AS CreditAvailable,"
+ " l.C_BPartner_Location_ID,c.AD_User_ID,"
+ " COALESCE(p.PO_PriceList_ID,g.PO_PriceList_ID) AS PO_PriceList_ID, p.PaymentRulePO,p.PO_PaymentTerm_ID "
+ "FROM C_BPartner p"
+ " INNER JOIN C_BP_Group g ON (p.C_BP_Group_ID=g.C_BP_Group_ID)"
+ " LEFT OUTER JOIN C_BPartner_Location l ON (p.C_BPartner_ID=l.C_BPartner_ID AND l.IsBillTo='Y' AND l.IsActive='Y')"
+ " LEFT OUTER JOIN AD_User c ON (p.C_BPartner_ID=c.C_BPartner_ID) "
+ "WHERE p.C_BPartner_ID=? AND p.IsActive='Y'"; // #1
boolean IsSOTrx = Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID.intValue());
ResultSet rs = pstmt.executeQuery();
//
if (rs.next())
{
// PaymentRule
String s = rs.getString(IsSOTrx ? "PaymentRule" : "PaymentRulePO");
if (s != null && s.length() != 0)
{
if (Env.getContext(ctx, WindowNo, "DocBaseType").endsWith("C")) // Credits are Payment Term
s = "P";
else if (IsSOTrx && (s.equals("S") || s.equals("U"))) // No Check/Transfer for SO_Trx
s = "P"; // Payment Term
// mTab.setValue("PaymentRule", s);
}
// Payment Term
Integer ii = new Integer(rs.getInt(IsSOTrx ? "C_PaymentTerm_ID" : "PO_PaymentTerm_ID"));
if (!rs.wasNull())
mTab.setValue("C_PaymentTerm_ID", ii);
// Location
int locID = rs.getInt("C_BPartner_Location_ID");
// overwritten by InfoBP selection - works only if InfoWindow
// was used otherwise creates error (uses last value, may belong to differnt BP)
if (C_BPartner_ID.toString().equals(Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_ID")))
{
String loc = Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_Location_ID");
if (loc.length() > 0)
locID = Integer.parseInt(loc);
}
if (locID == 0)
mTab.setValue("C_BPartner_Location_ID", null);
else
mTab.setValue("C_BPartner_Location_ID", new Integer(locID));
// Contact - overwritten by InfoBP selection
int contID = rs.getInt("AD_User_ID");
if (C_BPartner_ID.toString().equals(Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_BPartner_ID")))
{
String cont = Env.getContext(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "AD_User_ID");
if (cont.length() > 0)
contID = Integer.parseInt(cont);
}
if (contID == 0)
mTab.setValue("AD_User_ID", null);
else
mTab.setValue("AD_User_ID", new Integer(contID));
// CreditAvailable
if (IsSOTrx)
{
double CreditLimit = rs.getDouble("SO_CreditLimit");
if (CreditLimit != 0)
{
double CreditAvailable = rs.getDouble("CreditAvailable");
if (!rs.wasNull() && CreditAvailable < 0)
mTab.fireDataStatusEEvent("CreditLimitOver",
DisplayType.getNumberFormat(DisplayType.Amount).format(CreditAvailable),
false);
}
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return e.getLocalizedMessage();
}
//
setDocumentNo(ctx, WindowNo, mTab);
return tax (ctx, WindowNo, mTab, mField, value);
} // bPartner
/**
* Document Type.
* - called from DocType
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String docType (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
setDocumentNo(ctx, WindowNo, mTab);
return "";
} // docType
/**
* Set Document No (increase existing)
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
*/
private void setDocumentNo (Properties ctx, int WindowNo, GridTab mTab)
{
// Get last line
int C_InvoiceBatch_ID = Env.getContextAsInt(ctx, WindowNo, "C_InvoiceBatch_ID");
String sql = "SELECT COALESCE(MAX(C_InvoiceBatchLine_ID),0) FROM C_InvoiceBatchLine WHERE C_InvoiceBatch_ID=?";
int C_InvoiceBatchLine_ID = DB.getSQLValue(null, sql, C_InvoiceBatch_ID);
if (C_InvoiceBatchLine_ID == 0)
return;
MInvoiceBatchLine last = new MInvoiceBatchLine(Env.getCtx(), C_InvoiceBatchLine_ID, null);
// Need to Increase when different DocType or BP
int C_DocType_ID = Env.getContextAsInt(ctx, WindowNo, "C_DocType_ID");
int C_BPartner_ID = Env.getContextAsInt(ctx, WindowNo, "C_BPartner_ID");
if (C_DocType_ID == last.getC_DocType_ID()
&& C_BPartner_ID == last.getC_BPartner_ID())
return;
// New Number
String oldDocNo = last.getDocumentNo();
if (oldDocNo == null)
return;
int docNo = 0;
try
{
docNo = Integer.parseInt(oldDocNo);
}
catch (Exception e)
{
}
if (docNo == 0)
return;
String newDocNo = String.valueOf(docNo+1);
mTab.setValue("DocumentNo", newDocNo);
} // setDocumentNo
/**
* Invoice Batch Line - Charge.
* - updates PriceEntered from Charge
* Calles tax
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String charge (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Charge_ID = (Integer)value;
if (C_Charge_ID == null || C_Charge_ID.intValue() == 0)
return "";
String sql = "SELECT ChargeAmt FROM C_Charge WHERE C_Charge_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Charge_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
mTab.setValue ("PriceEntered", rs.getBigDecimal (1));
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return e.getLocalizedMessage();
}
//
return tax (ctx, WindowNo, mTab, mField, value);
} // charge
/**
* Invoice Line - Tax.
* - basis: Charge, BPartner Location
* - sets C_Tax_ID
* Calles Amount
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String tax (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String column = mField.getColumnName();
if (value == null)
return "";
int C_Charge_ID = 0;
if (column.equals("C_Charge_ID"))
C_Charge_ID = ((Integer)value).intValue();
else
C_Charge_ID = Env.getContextAsInt(ctx, WindowNo, "C_Charge_ID");
log.fine("C_Charge_ID=" + C_Charge_ID);
if (C_Charge_ID == 0)
return amt (ctx, WindowNo, mTab, mField, value); //
// Check Partner Location
int C_BPartner_Location_ID = Env.getContextAsInt(ctx, WindowNo, "C_BPartner_Location_ID");
if (C_BPartner_Location_ID == 0)
return amt (ctx, WindowNo, mTab, mField, value); //
log.fine("BP_Location=" + C_BPartner_Location_ID);
// Dates
Timestamp billDate = Env.getContextAsDate(ctx, WindowNo, "DateInvoiced");
log.fine("Bill Date=" + billDate);
Timestamp shipDate = billDate;
log.fine("Ship Date=" + shipDate);
int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
log.fine("Org=" + AD_Org_ID);
int M_Warehouse_ID = Env.getContextAsInt(ctx, "#M_Warehouse_ID");
log.fine("Warehouse=" + M_Warehouse_ID);
//
int C_Tax_ID = Tax.get(ctx, 0, C_Charge_ID, billDate, shipDate,
AD_Org_ID, M_Warehouse_ID, C_BPartner_Location_ID, C_BPartner_Location_ID,
Env.getContext(ctx, WindowNo, "IsSOTrx").equals("Y"));
log.info("Tax ID=" + C_Tax_ID);
//
if (C_Tax_ID == 0)
mTab.fireDataStatusEEvent(CLogger.retrieveError());
else
mTab.setValue("C_Tax_ID", new Integer(C_Tax_ID));
//
return amt (ctx, WindowNo, mTab, mField, value);
} // tax
/**
* Invoice - Amount.
* - called from QtyEntered, PriceEntered
* - calculates LineNetAmt
* @param ctx context
* @param WindowNo window no
* @param mTab tab
* @param mField field
* @param value value
* @return null or error message
*/
public String amt (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
int StdPrecision = 2; // temporary
// get values
BigDecimal QtyEntered = (BigDecimal)mTab.getValue("QtyEntered");
BigDecimal PriceEntered = (BigDecimal)mTab.getValue("PriceEntered");
log.fine("QtyEntered=" + QtyEntered + ", PriceEntered=" + PriceEntered);
if (QtyEntered == null)
QtyEntered = Env.ZERO;
if (PriceEntered == null)
PriceEntered = Env.ZERO;
// Line Net Amt
BigDecimal LineNetAmt = QtyEntered.multiply(PriceEntered);
if (LineNetAmt.scale() > StdPrecision)
LineNetAmt = LineNetAmt.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
// Calculate Tax Amount
boolean IsSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx"));
boolean IsTaxIncluded = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsTaxIncluded"));
BigDecimal TaxAmt = null;
if (mField.getColumnName().equals("TaxAmt"))
{
TaxAmt = (BigDecimal)mTab.getValue("TaxAmt");
}
else
{
Integer taxID = (Integer)mTab.getValue("C_Tax_ID");
if (taxID != null)
{
int C_Tax_ID = taxID.intValue();
MTax tax = new MTax (ctx, C_Tax_ID, null);
TaxAmt = tax.calculateTax(LineNetAmt, IsTaxIncluded, StdPrecision);
mTab.setValue("TaxAmt", TaxAmt);
}
}
//
if (IsTaxIncluded)
{
mTab.setValue("LineTotalAmt", LineNetAmt);
mTab.setValue("LineNetAmt", LineNetAmt.subtract(TaxAmt));
}
else
{
mTab.setValue("LineNetAmt", LineNetAmt);
mTab.setValue("LineTotalAmt", LineNetAmt.add(TaxAmt));
}
setCalloutActive(false);
return "";
} // amt
} // CalloutInvoiceBatch

View File

@ -0,0 +1,55 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
import org.compiere.util.*;
/**
* Inventory Movement Callouts
*
* @author Jorg Janke
* @version $Id: CalloutMovement.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutMovement extends CalloutEngine
{
/**
* Product modified
* Set Attribute Set Instance
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
// Set Attribute
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
mTab.setValue("M_AttributeSetInstance_ID", new Integer(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
else
mTab.setValue("M_AttributeSetInstance_ID", null);
return "";
} // product
} // CalloutMove

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,137 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Payment Selection Callouts
*
* @author Jorg Janke
* @version $Id: CalloutPaySelection.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class CalloutPaySelection extends CalloutEngine
{
/**
* Payment Selection Line - Payment Amount.
* - called from C_PaySelectionLine.PayAmt
* - update DifferenceAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String payAmt (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
// get invoice info
Integer ii = (Integer)mTab.getValue("C_Invoice_ID");
if (ii == null)
return "";
int C_Invoice_ID = ii.intValue();
if (C_Invoice_ID == 0)
return "";
//
BigDecimal OpenAmt = (BigDecimal)mTab.getValue("OpenAmt");
BigDecimal PayAmt = (BigDecimal)mTab.getValue("PayAmt");
BigDecimal DiscountAmt = (BigDecimal)mTab.getValue("DiscountAmt");
setCalloutActive(true);
BigDecimal DifferenceAmt = OpenAmt.subtract(PayAmt).subtract(DiscountAmt);
log.fine(" - OpenAmt=" + OpenAmt + " - PayAmt=" + PayAmt
+ ", Discount=" + DiscountAmt + ", Difference=" + DifferenceAmt);
mTab.setValue("DifferenceAmt", DifferenceAmt);
setCalloutActive(false);
return "";
} // PaySel_PayAmt
/**
* Payment Selection Line - Invoice.
* - called from C_PaySelectionLine.C_Invoice_ID
* - update PayAmt & DifferenceAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String invoice (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
// get value
int C_Invoice_ID = ((Integer)value).intValue();
if (C_Invoice_ID == 0)
return "";
int C_BankAccount_ID = Env.getContextAsInt(ctx, WindowNo, "C_BankAccount_ID");
Timestamp PayDate = Env.getContextAsDate(ctx, "PayDate");
if (PayDate == null)
PayDate = new Timestamp(System.currentTimeMillis());
setCalloutActive(true);
BigDecimal OpenAmt = Env.ZERO;
BigDecimal DiscountAmt = Env.ZERO;
Boolean IsSOTrx = Boolean.FALSE;
String sql = "SELECT currencyConvert(invoiceOpen(i.C_Invoice_ID, 0), i.C_Currency_ID,"
+ "ba.C_Currency_ID, i.DateInvoiced, i.C_ConversionType_ID, i.AD_Client_ID, i.AD_Org_ID),"
+ " paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?), i.IsSOTrx "
+ "FROM C_Invoice_v i, C_BankAccount ba "
+ "WHERE i.C_Invoice_ID=? AND ba.C_BankAccount_ID=?"; // #1..2
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Invoice_ID);
pstmt.setInt(2, C_BankAccount_ID);
pstmt.setTimestamp(3, PayDate);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
OpenAmt = rs.getBigDecimal(1);
DiscountAmt = rs.getBigDecimal(2);
IsSOTrx = new Boolean ("Y".equals(rs.getString(3)));
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
log.fine(" - OpenAmt=" + OpenAmt + " (Invoice=" + C_Invoice_ID + ",BankAcct=" + C_BankAccount_ID + ")");
mTab.setValue("OpenAmt", OpenAmt);
mTab.setValue("PayAmt", OpenAmt.subtract(DiscountAmt));
mTab.setValue("DiscountAmt", DiscountAmt);
mTab.setValue("DifferenceAmt", Env.ZERO);
mTab.setValue("IsSOTrx", IsSOTrx);
setCalloutActive(false);
return "";
} // PaySel_Invoice
} // CalloutPaySelection

View File

@ -0,0 +1,444 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Payment Callouts.
* org.compiere.model.CalloutPayment.*
*
* @author Jorg Janke
* @version $Id: CalloutPayment.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutPayment extends CalloutEngine
{
/**
* Payment_Invoice.
* when Invoice selected
* - set C_Currency_ID
* - C_BPartner_ID
* - DiscountAmt = C_Invoice_Discount (ID, DateTrx)
* - PayAmt = invoiceOpen (ID) - Discount
* - WriteOffAmt = 0
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String invoice (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Invoice_ID = (Integer)value;
if (isCalloutActive() // assuming it is resetting value
|| C_Invoice_ID == null || C_Invoice_ID.intValue() == 0)
return "";
setCalloutActive(true);
mTab.setValue("C_Order_ID", null);
mTab.setValue("C_Charge_ID", null);
mTab.setValue("IsPrepayment", Boolean.FALSE);
//
mTab.setValue("DiscountAmt", Env.ZERO);
mTab.setValue("WriteOffAmt", Env.ZERO);
mTab.setValue("IsOverUnderPayment", Boolean.FALSE);
mTab.setValue("OverUnderAmt", Env.ZERO);
int C_InvoicePaySchedule_ID = 0;
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0)
C_InvoicePaySchedule_ID = Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID");
// Payment Date
Timestamp ts = (Timestamp)mTab.getValue("DateTrx");
if (ts == null)
ts = new Timestamp(System.currentTimeMillis());
//
String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2
+ " invoiceOpen(C_Invoice_ID, ?)," // 3 #1
+ " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3
+ "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_InvoicePaySchedule_ID);
pstmt.setTimestamp(2, ts);
pstmt.setInt(3, C_InvoicePaySchedule_ID);
pstmt.setInt(4, C_Invoice_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
mTab.setValue("C_BPartner_ID", new Integer(rs.getInt(1)));
int C_Currency_ID = rs.getInt(2); // Set Invoice Currency
mTab.setValue("C_Currency_ID", new Integer(C_Currency_ID));
//
BigDecimal InvoiceOpen = rs.getBigDecimal(3); // Set Invoice OPen Amount
if (InvoiceOpen == null)
InvoiceOpen = Env.ZERO;
BigDecimal DiscountAmt = rs.getBigDecimal(4); // Set Discount Amt
if (DiscountAmt == null)
DiscountAmt = Env.ZERO;
mTab.setValue("PayAmt", InvoiceOpen.subtract(DiscountAmt));
mTab.setValue("DiscountAmt", DiscountAmt);
// reset as dependent fields get reset
Env.setContext(ctx, WindowNo, "C_Invoice_ID", C_Invoice_ID.toString());
mTab.setValue("C_Invoice_ID", C_Invoice_ID);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
setCalloutActive(false);
return docType(ctx, WindowNo, mTab, mField, value);
} // invoice
/**
* Payment_Order.
* when Waiting Payment Order selected
* - set C_Currency_ID
* - C_BPartner_ID
* - DiscountAmt = C_Invoice_Discount (ID, DateTrx)
* - PayAmt = invoiceOpen (ID) - Discount
* - WriteOffAmt = 0
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String order (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Order_ID = (Integer)value;
if (isCalloutActive() // assuming it is resetting value
|| C_Order_ID == null || C_Order_ID.intValue() == 0)
return "";
setCalloutActive(true);
mTab.setValue("C_Invoice_ID", null);
mTab.setValue("C_Charge_ID", null);
mTab.setValue("IsPrepayment", Boolean.TRUE);
//
mTab.setValue("DiscountAmt", Env.ZERO);
mTab.setValue("WriteOffAmt", Env.ZERO);
mTab.setValue("IsOverUnderPayment", Boolean.FALSE);
mTab.setValue("OverUnderAmt", Env.ZERO);
// Payment Date
Timestamp ts = (Timestamp)mTab.getValue("DateTrx");
if (ts == null)
ts = new Timestamp(System.currentTimeMillis());
//
String sql = "SELECT C_BPartner_ID,C_Currency_ID, GrandTotal "
+ "FROM C_Order WHERE C_Order_ID=?"; // #1
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_Order_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
mTab.setValue("C_BPartner_ID", new Integer(rs.getInt(1)));
int C_Currency_ID = rs.getInt(2); // Set Order Currency
mTab.setValue("C_Currency_ID", new Integer(C_Currency_ID));
//
BigDecimal GrandTotal = rs.getBigDecimal(3); // Set Pay Amount
if (GrandTotal == null)
GrandTotal = Env.ZERO;
mTab.setValue("PayAmt", GrandTotal);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
setCalloutActive(false);
return docType(ctx, WindowNo, mTab, mField, value);
} // order
/**
* Payment_Project.
* - reset - C_BPartner_ID, Invoice, Order, Project,
* Discount, WriteOff
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String project (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Project_ID = (Integer)value;
if (isCalloutActive() // assuming it is resetting value
|| C_Project_ID == null || C_Project_ID.intValue() == 0)
return "";
setCalloutActive(true);
mTab.setValue("C_Charge_ID", null);
setCalloutActive(false);
return "";
} // project
/**
* Payment_Charge.
* - reset - C_BPartner_ID, Invoice, Order, Project,
* Discount, WriteOff
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String charge (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Charge_ID = (Integer)value;
if (isCalloutActive() // assuming it is resetting value
|| C_Charge_ID == null || C_Charge_ID.intValue() == 0)
return "";
setCalloutActive(true);
mTab.setValue("C_Invoice_ID", null);
mTab.setValue("C_Order_ID", null);
mTab.setValue("C_Project_ID", null);
mTab.setValue("IsPrepayment", Boolean.FALSE);
//
mTab.setValue("DiscountAmt", Env.ZERO);
mTab.setValue("WriteOffAmt", Env.ZERO);
mTab.setValue("IsOverUnderPayment", Boolean.FALSE);
mTab.setValue("OverUnderAmt", Env.ZERO);
setCalloutActive(false);
return "";
} // charge
/**
* Payment_Document Type.
* Verify that Document Type (AP/AR) and Invoice (SO/PO) are in sync
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String docType (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
int C_Invoice_ID = Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID");
int C_Order_ID = Env.getContextAsInt(ctx, WindowNo, "C_Order_ID");
int C_DocType_ID = Env.getContextAsInt(ctx, WindowNo, "C_DocType_ID");
log.fine("Payment_DocType - C_Invoice_ID=" + C_Invoice_ID + ", C_DocType_ID=" + C_DocType_ID);
MDocType dt = null;
if (C_DocType_ID != 0)
{
dt = MDocType.get(ctx, C_DocType_ID);
Env.setContext(ctx, WindowNo, "IsSOTrx", dt.isSOTrx() ? "Y" : "N");
}
// Invoice
if (C_Invoice_ID != 0)
{
MInvoice inv = new MInvoice (ctx, C_Invoice_ID, null);
if (dt != null)
{
if (inv.isSOTrx() != dt.isSOTrx())
return "PaymentDocTypeInvoiceInconsistent";
}
}
// Order Waiting Payment (can only be SO)
if (C_Order_ID != 0 && !dt.isSOTrx())
return "PaymentDocTypeInvoiceInconsistent";
return "";
} // docType
/**
* Payment_Amounts.
* Change of:
* - IsOverUnderPayment -> set OverUnderAmt to 0
* - C_Currency_ID, C_ConvesionRate_ID -> convert all
* - PayAmt, DiscountAmt, WriteOffAmt, OverUnderAmt -> PayAmt
* make sure that add up to InvoiceOpenAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @param oldValue Old Value
* @return null or error message
*/
public String amounts (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value, Object oldValue)
{
if (isCalloutActive()) // assuming it is resetting value
return "";
int C_Invoice_ID = Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID");
// New Payment
if (Env.getContextAsInt(ctx, WindowNo, "C_Payment_ID") == 0
&& Env.getContextAsInt(ctx, WindowNo, "C_BPartner_ID") == 0
&& C_Invoice_ID == 0)
return "";
setCalloutActive(true);
// Changed Column
String colName = mField.getColumnName();
if (colName.equals("IsOverUnderPayment") // Set Over/Under Amt to Zero
|| !"Y".equals(Env.getContext(ctx, WindowNo, "IsOverUnderPayment")))
mTab.setValue("OverUnderAmt", Env.ZERO);
int C_InvoicePaySchedule_ID = 0;
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0)
C_InvoicePaySchedule_ID = Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID");
// Get Open Amount & Invoice Currency
BigDecimal InvoiceOpenAmt = Env.ZERO;
int C_Currency_Invoice_ID = 0;
if (C_Invoice_ID != 0)
{
Timestamp ts = (Timestamp)mTab.getValue("DateTrx");
if (ts == null)
ts = new Timestamp(System.currentTimeMillis());
String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2
+ " invoiceOpen(C_Invoice_ID,?)," // 3 #1
+ " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3
+ "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_InvoicePaySchedule_ID);
pstmt.setTimestamp(2, ts);
pstmt.setInt(3, C_InvoicePaySchedule_ID);
pstmt.setInt(4, C_Invoice_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
C_Currency_Invoice_ID= rs.getInt(2);
InvoiceOpenAmt = rs.getBigDecimal(3); // Set Invoice Open Amount
if (InvoiceOpenAmt == null)
InvoiceOpenAmt = Env.ZERO;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
} // get Invoice Info
log.fine("Open=" + InvoiceOpenAmt + ", C_Invoice_ID=" + C_Invoice_ID
+ ", C_Currency_ID=" + C_Currency_Invoice_ID);
// Get Info from Tab
BigDecimal PayAmt = (BigDecimal)mTab.getValue("PayAmt");
BigDecimal DiscountAmt = (BigDecimal)mTab.getValue("DiscountAmt");
BigDecimal WriteOffAmt = (BigDecimal)mTab.getValue("WriteOffAmt");
BigDecimal OverUnderAmt = (BigDecimal)mTab.getValue("OverUnderAmt");
log.fine("Pay=" + PayAmt + ", Discount=" + DiscountAmt
+ ", WriteOff=" + WriteOffAmt + ", OverUnderAmt=" + OverUnderAmt);
// Get Currency Info
int C_Currency_ID = ((Integer)mTab.getValue("C_Currency_ID")).intValue();
MCurrency currency = MCurrency.get(ctx, C_Currency_ID);
Timestamp ConvDate = (Timestamp)mTab.getValue("DateTrx");
int C_ConversionType_ID = 0;
Integer ii = (Integer)mTab.getValue("C_ConversionType_ID");
if (ii != null)
C_ConversionType_ID = ii.intValue();
int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID");
int AD_Org_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Org_ID");
// Get Currency Rate
BigDecimal CurrencyRate = Env.ONE;
if ((C_Currency_ID > 0 && C_Currency_Invoice_ID > 0 &&
C_Currency_ID != C_Currency_Invoice_ID)
|| colName.equals("C_Currency_ID") || colName.equals("C_ConversionType_ID"))
{
log.fine("InvCurrency=" + C_Currency_Invoice_ID
+ ", PayCurrency=" + C_Currency_ID
+ ", Date=" + ConvDate + ", Type=" + C_ConversionType_ID);
CurrencyRate = MConversionRate.getRate (C_Currency_Invoice_ID, C_Currency_ID,
ConvDate, C_ConversionType_ID, AD_Client_ID, AD_Org_ID);
if (CurrencyRate == null || CurrencyRate.compareTo(Env.ZERO) == 0)
{
// mTab.setValue("C_Currency_ID", new Integer(C_Currency_Invoice_ID)); // does not work
setCalloutActive(false);
if (C_Currency_Invoice_ID == 0)
return ""; // no error message when no invoice is selected
return "NoCurrencyConversion";
}
//
InvoiceOpenAmt = InvoiceOpenAmt.multiply(CurrencyRate)
.setScale(currency.getStdPrecision(), BigDecimal.ROUND_HALF_UP);
log.fine("Rate=" + CurrencyRate + ", InvoiceOpenAmt=" + InvoiceOpenAmt);
}
// Currency Changed - convert all
if (colName.equals("C_Currency_ID") || colName.equals("C_ConversionType_ID"))
{
PayAmt = PayAmt.multiply(CurrencyRate)
.setScale(currency.getStdPrecision(), BigDecimal.ROUND_HALF_UP);
mTab.setValue("PayAmt", PayAmt);
DiscountAmt = DiscountAmt.multiply(CurrencyRate)
.setScale(currency.getStdPrecision(), BigDecimal.ROUND_HALF_UP);
mTab.setValue("DiscountAmt", DiscountAmt);
WriteOffAmt = WriteOffAmt.multiply(CurrencyRate)
.setScale(currency.getStdPrecision(), BigDecimal.ROUND_HALF_UP);
mTab.setValue("WriteOffAmt", WriteOffAmt);
OverUnderAmt = OverUnderAmt.multiply(CurrencyRate)
.setScale(currency.getStdPrecision(), BigDecimal.ROUND_HALF_UP);
mTab.setValue("OverUnderAmt", OverUnderAmt);
}
// No Invoice - Set Discount, Witeoff, Under/Over to 0
else if (C_Invoice_ID == 0)
{
if (Env.ZERO.compareTo(DiscountAmt) != 0)
mTab.setValue("DiscountAmt", Env.ZERO);
if (Env.ZERO.compareTo(WriteOffAmt) != 0)
mTab.setValue("WriteOffAmt", Env.ZERO);
if (Env.ZERO.compareTo(OverUnderAmt) != 0)
mTab.setValue("OverUnderAmt", Env.ZERO);
}
// PayAmt - calculate write off
else if (colName.equals("PayAmt"))
{
WriteOffAmt = InvoiceOpenAmt.subtract(PayAmt).subtract(DiscountAmt).subtract(OverUnderAmt);
mTab.setValue("WriteOffAmt", WriteOffAmt);
}
else // calculate PayAmt
{
PayAmt = InvoiceOpenAmt.subtract(DiscountAmt).subtract(WriteOffAmt).subtract(OverUnderAmt);
mTab.setValue("PayAmt", PayAmt);
}
setCalloutActive(false);
return "";
} // amounts
} // CalloutPayment

View File

@ -0,0 +1,174 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Callout for Allocate Payments
*
* @author Jorg Janke
* @version $Id: CalloutPaymentAllocate.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class CalloutPaymentAllocate extends CalloutEngine
{
/**
* Payment_Invoice.
* when Invoice selected
* - set InvoiceAmt = invoiceOpen
* - DiscountAmt = C_Invoice_Discount (ID, DateTrx)
* - Amount = invoiceOpen (ID) - Discount
* - WriteOffAmt,OverUnderAmt = 0
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String invoice (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer C_Invoice_ID = (Integer)value;
if (isCalloutActive() // assuming it is resetting value
|| C_Invoice_ID == null || C_Invoice_ID.intValue() == 0)
return "";
// Check Payment
int C_Payment_ID = Env.getContextAsInt(ctx, WindowNo, "C_Payment_ID");
MPayment payment = new MPayment (ctx, C_Payment_ID, null);
if (payment.getC_Charge_ID() != 0 || payment.getC_Invoice_ID() != 0
|| payment.getC_Order_ID() != 0)
return Msg.getMsg(ctx, "PaymentIsAllocated");
setCalloutActive(true);
//
mTab.setValue("DiscountAmt", Env.ZERO);
mTab.setValue("WriteOffAmt", Env.ZERO);
mTab.setValue("OverUnderAmt", Env.ZERO);
int C_InvoicePaySchedule_ID = 0;
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_Invoice_ID") == C_Invoice_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID") != 0)
C_InvoicePaySchedule_ID = Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "C_InvoicePaySchedule_ID");
// Payment Date
Timestamp ts = Env.getContextAsDate(ctx, WindowNo, "DateTrx");
//
String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2
+ " invoiceOpen(C_Invoice_ID, ?)," // 3 #1
+ " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3
+ "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_InvoicePaySchedule_ID);
pstmt.setTimestamp(2, ts);
pstmt.setInt(3, C_InvoicePaySchedule_ID);
pstmt.setInt(4, C_Invoice_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// mTab.setValue("C_BPartner_ID", new Integer(rs.getInt(1)));
// int C_Currency_ID = rs.getInt(2); // Set Invoice Currency
// mTab.setValue("C_Currency_ID", new Integer(C_Currency_ID));
//
BigDecimal InvoiceOpen = rs.getBigDecimal(3); // Set Invoice OPen Amount
if (InvoiceOpen == null)
InvoiceOpen = Env.ZERO;
BigDecimal DiscountAmt = rs.getBigDecimal(4); // Set Discount Amt
if (DiscountAmt == null)
DiscountAmt = Env.ZERO;
mTab.setValue("InvoiceAmt", InvoiceOpen);
mTab.setValue("Amount", InvoiceOpen.subtract(DiscountAmt));
mTab.setValue("DiscountAmt", DiscountAmt);
// reset as dependent fields get reset
Env.setContext(ctx, WindowNo, "C_Invoice_ID", C_Invoice_ID.toString());
mTab.setValue("C_Invoice_ID", C_Invoice_ID);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
setCalloutActive(false);
return "";
} // invoice
/**
* Payment_Amounts.
* Change of:
* - IsOverUnderPayment -> set OverUnderAmt to 0
* - C_Currency_ID, C_ConvesionRate_ID -> convert all
* - PayAmt, DiscountAmt, WriteOffAmt, OverUnderAmt -> PayAmt
* make sure that add up to InvoiceOpenAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @param oldValue Old Value
* @return null or error message
*/
public String amounts (Properties ctx, int WindowNo, GridTab mTab, GridField mField,
Object value, Object oldValue)
{
if (isCalloutActive()) // assuming it is resetting value
return "";
// No Invoice
int C_Invoice_ID = Env.getContextAsInt(ctx, WindowNo, "C_Invoice_ID");
if (C_Invoice_ID == 0)
return "";
setCalloutActive(true);
// Get Info from Tab
BigDecimal Amount = (BigDecimal)mTab.getValue("Amount");
BigDecimal DiscountAmt = (BigDecimal)mTab.getValue("DiscountAmt");
BigDecimal WriteOffAmt = (BigDecimal)mTab.getValue("WriteOffAmt");
BigDecimal OverUnderAmt = (BigDecimal)mTab.getValue("OverUnderAmt");
BigDecimal InvoiceAmt = (BigDecimal)mTab.getValue("InvoiceAmt");
log.fine("Amt=" + Amount + ", Discount=" + DiscountAmt
+ ", WriteOff=" + WriteOffAmt + ", OverUnder=" + OverUnderAmt
+ ", Invoice=" + InvoiceAmt);
// Changed Column
String colName = mField.getColumnName();
// PayAmt - calculate write off
if (colName.equals("Amount"))
{
WriteOffAmt = InvoiceAmt.subtract(Amount).subtract(DiscountAmt).subtract(OverUnderAmt);
mTab.setValue("WriteOffAmt", WriteOffAmt);
}
else // calculate Amount
{
Amount = InvoiceAmt.subtract(DiscountAmt).subtract(WriteOffAmt).subtract(OverUnderAmt);
mTab.setValue("Amount", Amount);
}
setCalloutActive(false);
return "";
} // amounts
} // CalloutPaymentAllocate

View File

@ -0,0 +1,55 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
import org.compiere.util.*;
/**
* Production Callouts
*
* @author Jorg Janke
* @version $Id: CalloutProduction.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutProduction extends CalloutEngine
{
/**
* Product modified
* Set Attribute Set Instance
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
// Set Attribute
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
mTab.setValue("M_AttributeSetInstance_ID", new Integer(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
else
mTab.setValue("M_AttributeSetInstance_ID", null);
return "";
} // product
} // CalloutProduction

View File

@ -0,0 +1,71 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.util.*;
import org.compiere.util.*;
/**
* Project Callouts
*
* @author Jorg Janke
* @version $Id: CalloutProject.java,v 1.3 2006/07/30 00:51:04 jjanke Exp $
*/
public class CalloutProject extends CalloutEngine
{
/**
* Project Planned - Price + Qty.
* - called from PlannedPrice, PlannedQty
* - calculates PlannedAmt (same as Trigger)
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String planned (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
BigDecimal PlannedQty, PlannedPrice;
int StdPrecision = Env.getContextAsInt(ctx, WindowNo, "StdPrecision");
// get values
PlannedQty = (BigDecimal)mTab.getValue("PlannedQty");
if (PlannedQty == null)
PlannedQty = Env.ONE;
PlannedPrice = ((BigDecimal)mTab.getValue("PlannedPrice"));
if (PlannedPrice == null)
PlannedPrice = Env.ZERO;
//
BigDecimal PlannedAmt = PlannedQty.multiply(PlannedPrice);
if (PlannedAmt.scale() > StdPrecision)
PlannedAmt = PlannedAmt.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
//
log.fine("PlannedQty=" + PlannedQty + " * PlannedPrice=" + PlannedPrice + " -> PlannedAmt=" + PlannedAmt + " (Precision=" + StdPrecision+ ")");
mTab.setValue("PlannedAmt", PlannedAmt);
setCalloutActive(false);
return "";
} // planned
} // CalloutProject

View File

@ -0,0 +1,142 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Request Callouts
*
* @author Jorg Janke
* @version $Id: CalloutRequest.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutRequest extends CalloutEngine
{
/**
* Request - Copy Mail Text - <b>Callout</b>
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String copyMail (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
log.info(colName + "=" + value);
if (value == null)
return "";
Integer R_MailText_ID = (Integer)value;
String sql = "SELECT MailHeader, MailText FROM R_MailText "
+ "WHERE R_MailText_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, R_MailText_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String txt = rs.getString(2);
txt = Env.parseContext(ctx, WindowNo, txt, false, true);
mTab.setValue("Result", txt);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
return "";
} // copyText
/**
* Request - Copy Response Text - <b>Callout</b>
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String copyResponse (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
log.info(colName + "=" + value);
if (value == null)
return "";
Integer R_StandardResponse_ID = (Integer)value;
String sql = "SELECT Name, ResponseText FROM R_StandardResponse "
+ "WHERE R_StandardResponse_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, R_StandardResponse_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String txt = rs.getString(2);
txt = Env.parseContext(ctx, WindowNo, txt, false, true);
mTab.setValue("Result", txt);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
return "";
} // copyResponse
/**
* Request - Chane of Request Type - <b>Callout</b>
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @return Error message or ""
*/
public String type (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
String colName = mField.getColumnName();
log.info(colName + "=" + value);
mTab.setValue("R_Status_ID", null);
if (value == null)
return "";
int R_RequestType_ID = ((Integer)value).intValue();
if (R_RequestType_ID == 0)
return "";
MRequestType rt = MRequestType.get(ctx, R_RequestType_ID);
int R_Status_ID = rt.getDefaultR_Status_ID();
if (R_Status_ID != 0)
mTab.setValue("R_Status_ID", new Integer(R_Status_ID));
return "";
} // type
} // CalloutRequest

View File

@ -0,0 +1,134 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Requisition Callouts
*
* @author Jorg Janke
* @version $Id: CalloutRequisition.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class CalloutRequisition extends CalloutEngine
{
/**
* Requisition Line - Product.
* - PriceStd
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
// setCalloutActive(true);
//
/** Set Attribute
if (Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID") == M_Product_ID.intValue()
&& Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID") != 0)
mTab.setValue("M_AttributeSetInstance_ID", new Integer(Env.getContextAsInt(ctx, Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID")));
else
mTab.setValue("M_AttributeSetInstance_ID", null);
**/
int C_BPartner_ID = Env.getContextAsInt(ctx, WindowNo, WindowNo, "C_BPartner_ID");
BigDecimal Qty = (BigDecimal)mTab.getValue("Qty");
boolean isSOTrx = false;
MProductPricing pp = new MProductPricing (M_Product_ID.intValue(),
C_BPartner_ID, Qty, isSOTrx);
//
int M_PriceList_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID");
pp.setM_PriceList_ID(M_PriceList_ID);
int M_PriceList_Version_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_Version_ID");
pp.setM_PriceList_Version_ID(M_PriceList_Version_ID);
Timestamp orderDate = (Timestamp)mTab.getValue("DateRequired");
pp.setPriceDate(orderDate);
//
mTab.setValue("PriceActual", pp.getPriceStd());
Env.setContext(ctx, WindowNo, "EnforcePriceLimit", pp.isEnforcePriceLimit() ? "Y" : "N"); // not used
Env.setContext(ctx, WindowNo, "DiscountSchema", pp.isDiscountSchema() ? "Y" : "N");
// setCalloutActive(false);
return "";
} // product
/**
* Order Line - Amount.
* - called from Qty, PriceActual
* - calculates LineNetAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String amt (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive() || value == null)
return "";
setCalloutActive(true);
// Qty changed - recalc price
if (mField.getColumnName().equals("Qty")
&& "Y".equals(Env.getContext(ctx, WindowNo, "DiscountSchema")))
{
int M_Product_ID = Env.getContextAsInt(ctx, WindowNo, WindowNo, "M_Product_ID");
int C_BPartner_ID = Env.getContextAsInt(ctx, WindowNo, WindowNo, "C_BPartner_ID");
BigDecimal Qty = (BigDecimal)value;
boolean isSOTrx = false;
MProductPricing pp = new MProductPricing (M_Product_ID,
C_BPartner_ID, Qty, isSOTrx);
//
int M_PriceList_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID");
pp.setM_PriceList_ID(M_PriceList_ID);
int M_PriceList_Version_ID = Env.getContextAsInt(ctx, WindowNo, "M_PriceList_Version_ID");
pp.setM_PriceList_Version_ID(M_PriceList_Version_ID);
Timestamp orderDate = (Timestamp)mTab.getValue("DateInvoiced");
pp.setPriceDate(orderDate);
//
mTab.setValue("PriceActual", pp.getPriceStd());
}
int StdPrecision = Env.getContextAsInt(ctx, WindowNo, "StdPrecision");
BigDecimal Qty = (BigDecimal)mTab.getValue("Qty");
BigDecimal PriceActual = (BigDecimal)mTab.getValue("PriceActual");
// get values
log.fine("amt - Qty=" + Qty + ", Price=" + PriceActual + ", Precision=" + StdPrecision);
// Multiply
BigDecimal LineNetAmt = Qty.multiply(PriceActual);
if (LineNetAmt.scale() > StdPrecision)
LineNetAmt = LineNetAmt.setScale(StdPrecision, BigDecimal.ROUND_HALF_UP);
mTab.setValue("LineNetAmt", LineNetAmt);
log.info("amt - LineNetAmt=" + LineNetAmt);
//
setCalloutActive(false);
return "";
} // amt
} // CalloutRequisition

View File

@ -0,0 +1,206 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Time & Expense Report Callout
*
* @author Jorg Janke
* @version $Id: CalloutTimeExpense.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class CalloutTimeExpense extends CalloutEngine
{
/**
* Expense Report Line
* - called from M_Product_ID, S_ResourceAssignment_ID
* - set ExpenseAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String product (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
Integer M_Product_ID = (Integer)value;
if (M_Product_ID == null || M_Product_ID.intValue() == 0)
return "";
setCalloutActive(true);
BigDecimal priceActual = null;
// get expense date - or default to today's date
Timestamp DateExpense = Env.getContextAsDate(ctx, WindowNo, "DateExpense");
if (DateExpense == null)
DateExpense = new Timestamp(System.currentTimeMillis());
String sql = null;
try
{
boolean noPrice = true;
// Search Pricelist for current version
sql = "SELECT bomPriceStd(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceStd,"
+ "bomPriceList(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceList,"
+ "bomPriceLimit(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceLimit,"
+ "p.C_UOM_ID,pv.ValidFrom,pl.C_Currency_ID "
+ "FROM M_Product p, M_ProductPrice pp, M_Pricelist pl, M_PriceList_Version pv "
+ "WHERE p.M_Product_ID=pp.M_Product_ID"
+ " AND pp.M_PriceList_Version_ID=pv.M_PriceList_Version_ID"
+ " AND pv.M_PriceList_ID=pl.M_PriceList_ID"
+ " AND pv.IsActive='Y'"
+ " AND p.M_Product_ID=?" // 1
+ " AND pl.M_PriceList_ID=?" // 2
+ " ORDER BY pv.ValidFrom DESC";
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID.intValue());
pstmt.setInt(2, Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID"));
ResultSet rs = pstmt.executeQuery();
while (rs.next() && noPrice)
{
java.sql.Date plDate = rs.getDate("ValidFrom");
// we have the price list
// if order date is after or equal PriceList validFrom
if (plDate == null || !DateExpense.before(plDate))
{
noPrice = false;
// Price
priceActual = rs.getBigDecimal("PriceStd");
if (priceActual == null)
priceActual = rs.getBigDecimal("PriceList");
if (priceActual == null)
priceActual = rs.getBigDecimal("PriceLimit");
// Currency
Integer ii = new Integer(rs.getInt("C_Currency_ID"));
if (!rs.wasNull())
mTab.setValue("C_Currency_ID", ii);
}
}
rs.close();
pstmt.close();
// no prices yet - look base pricelist
if (noPrice)
{
// Find if via Base Pricelist
sql = "SELECT bomPriceStd(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceStd,"
+ "bomPriceList(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceList,"
+ "bomPriceLimit(p.M_Product_ID,pv.M_PriceList_Version_ID) AS PriceLimit,"
+ "p.C_UOM_ID,pv.ValidFrom,pl.C_Currency_ID "
+ "FROM M_Product p, M_ProductPrice pp, M_Pricelist pl, M_Pricelist bpl, M_PriceList_Version pv "
+ "WHERE p.M_Product_ID=pp.M_Product_ID"
+ " AND pp.M_PriceList_Version_ID=pv.M_PriceList_Version_ID"
+ " AND pv.M_PriceList_ID=bpl.M_PriceList_ID"
+ " AND pv.IsActive='Y'"
+ " AND bpl.M_PriceList_ID=pl.BasePriceList_ID" // Base
+ " AND p.M_Product_ID=?" // 1
+ " AND pl.M_PriceList_ID=?" // 2
+ " ORDER BY pv.ValidFrom DESC";
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID.intValue());
pstmt.setInt(2, Env.getContextAsInt(ctx, WindowNo, "M_PriceList_ID"));
rs = pstmt.executeQuery();
while (rs.next() && noPrice)
{
java.sql.Date plDate = rs.getDate("ValidFrom");
// we have the price list
// if order date is after or equal PriceList validFrom
if (plDate == null || !DateExpense.before(plDate))
{
noPrice = false;
// Price
priceActual = rs.getBigDecimal("PriceStd");
if (priceActual == null)
priceActual = rs.getBigDecimal("PriceList");
if (priceActual == null)
priceActual = rs.getBigDecimal("PriceLimit");
// Currency
Integer ii = new Integer(rs.getInt("C_Currency_ID"));
if (!rs.wasNull())
mTab.setValue("C_Currency_ID", ii);
}
}
rs.close();
pstmt.close();
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
setCalloutActive(false);
return e.getLocalizedMessage();
}
// finish
setCalloutActive(false); // calculate amount
if (priceActual == null)
priceActual = Env.ZERO;
mTab.setValue("ExpenseAmt", priceActual);
return "";
} // Expense_Product
/**
* Expense - Amount.
* - called from ExpenseAmt, C_Currency_ID
* - calculates ConvertedAmt
* @param ctx context
* @param WindowNo current Window No
* @param mTab Grid Tab
* @param mField Grid Field
* @param value New Value
* @return null or error message
*/
public String amount (Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
if (isCalloutActive())
return "";
setCalloutActive(true);
// get values
BigDecimal ExpenseAmt = (BigDecimal)mTab.getValue("ExpenseAmt");
Integer C_Currency_From_ID = (Integer)mTab.getValue("C_Currency_ID");
int C_Currency_To_ID = Env.getContextAsInt(ctx, "$C_Currency_ID");
Timestamp DateExpense = Env.getContextAsDate(ctx, WindowNo, "DateExpense");
//
log.fine("Amt=" + ExpenseAmt + ", C_Currency_ID=" + C_Currency_From_ID);
// Converted Amount = Unit price
BigDecimal ConvertedAmt = ExpenseAmt;
// convert if required
if (!ConvertedAmt.equals(Env.ZERO) && C_Currency_To_ID != C_Currency_From_ID.intValue())
{
int AD_Client_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Client_ID");
int AD_Org_ID = Env.getContextAsInt (ctx, WindowNo, "AD_Org_ID");
ConvertedAmt = MConversionRate.convert (ctx,
ConvertedAmt, C_Currency_From_ID.intValue(), C_Currency_To_ID,
DateExpense, 0, AD_Client_ID, AD_Org_ID);
}
mTab.setValue("ConvertedAmt", ConvertedAmt);
log.fine("= ConvertedAmt=" + ConvertedAmt);
setCalloutActive(false);
return "";
} // Expense_Amount
} // CalloutTimeExpense

View File

@ -0,0 +1,335 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.io.*;
import java.sql.*;
import java.util.*;
/**
* Data Status Event
* <p>
* Indicates the current Status of the database
*
* @author Jorg Janke
* @version $Id: DataStatusEvent.java,v 1.4 2006/07/30 00:51:02 jjanke Exp $
*/
public final class DataStatusEvent extends EventObject implements Serializable
{
/**
* Constructor
* @param source1 source
* @param totalRows total rows
* @param changed changed
* @param autoSave auto save
* @param inserting inserting
*/
public DataStatusEvent (Object source1, int totalRows, boolean changed,
boolean autoSave, boolean inserting)
{
super(source1);
m_totalRows = totalRows;
m_changed = changed;
m_autoSave = autoSave;
m_inserting = inserting;
} // DataStatusEvent
private int m_totalRows;
private boolean m_changed;
private boolean m_autoSave;
private boolean m_inserting;
//
private String m_AD_Message = null;
private String m_info = null;
private boolean m_isError = false;
private boolean m_isWarning = false;
private boolean m_confirmed = false;
//
private boolean m_allLoaded = true;
private int m_loadedRows = -1;
private int m_currentRow = -1;
//
private int m_changedColumn = 0;
private String m_columnName = null;
/** Created */
public Timestamp Created = null;
/** Created By */
public Integer CreatedBy = null;
/** Updated */
public Timestamp Updated = null;
/** Updated By */
public Integer UpdatedBy = null;
/** Info */
public String Info = null;
/** Table ID */
public int AD_Table_ID = 0;
/** Record ID */
public Object Record_ID = null;
/**
* Set Loaded Info
* @param loadedRows loaded rows
*/
public void setLoading (int loadedRows)
{
m_allLoaded = false;
m_loadedRows = loadedRows;
} // setLoaded
/**
* Is loading
* @return true if loading
*/
public boolean isLoading()
{
return !m_allLoaded;
} // isLoading
/**
* Get loaded rows
* @return loaded rows
*/
public int getLoadedRows()
{
return m_loadedRows;
} // getLoadedRows
/**
* Set current Row (zero based)
* @param currentRow current row
*/
public void setCurrentRow (int currentRow)
{
m_currentRow = currentRow;
} // setCurrentRow
/**
* Get current row (zero based)
* @return current roe
*/
public int getCurrentRow()
{
return m_currentRow;
} // getCurrentRow
/**
* Get total rows
* @return total rows
*/
public int getTotalRows()
{
return m_totalRows;
} // getTotalRows
/**
* Set Message Info
* @param AD_Message message
* @param info info
* @param isError error
* @param isWarning true if warning
*/
public void setInfo (String AD_Message, String info, boolean isError, boolean isWarning)
{
m_AD_Message = AD_Message;
m_info = info;
m_isError = isError;
m_isWarning = isWarning;
} // setInfo
/**
* Set Inserting
* @param inserting inserting
*/
public void setInserting (boolean inserting)
{
m_inserting = inserting;
} // setInserting
/**
* Are we inserting
* @return true if inserting
*/
public boolean isInserting()
{
return m_inserting;
} // isInserting
/**
* Get Message Info
* @return Message
*/
public String getAD_Message()
{
return m_AD_Message;
} // getAD_Message
/**
* Get Message Info
* @return Info
*/
public String getInfo()
{
return m_info;
} // getInfo
/**
* Is this an error
* @return true if error
*/
public boolean isError()
{
return m_isError;
} // isError
/**
* Is this a warning
* @return true if warning
*/
public boolean isWarning()
{
return m_isWarning;
} // isWarning
/**
* String representation of Status.
* @return Examples: +*1?/20
* 1/256->2000
*/
public String toString()
{
StringBuffer sb = new StringBuffer("DataStatusEvent - ");
if (m_AD_Message != null)
sb.append(m_AD_Message);
if (m_info != null)
sb.append(" ").append(m_info);
sb.append(" : ").append(getMessage());
return sb.toString();
} // toString
/**
* String representation of Status.
* <pre>
* *1/20 Change - automatic commit
* ?1/20 Change - manual confirm
* 1/56->200 Loading
* 1/20 Normal
* +*1/20 Inserting, changed - automatic commit
* The row number is converted from zero based representation
* </pre>
* @return Status info
*/
public String getMessage()
{
StringBuffer retValue = new StringBuffer();
if (m_inserting)
retValue.append("+");
retValue.append(m_changed ? (m_autoSave ? "*" : "?") : " ");
// current row
if (m_totalRows == 0)
retValue.append(m_currentRow);
else
retValue.append(m_currentRow+1);
// of
retValue.append("/");
if (m_allLoaded)
retValue.append(m_totalRows);
else
retValue.append(m_loadedRows).append("->").append(m_totalRows);
//
return retValue.toString();
} // getMessage
/**
* Is Data Changed
* @return true if changed
*/
public boolean isChanged()
{
return m_changed;
} // isChanged
/**
* Is First Row - (zero based)
* @return true if first row
*/
public boolean isFirstRow()
{
if (m_totalRows == 0)
return true;
return m_currentRow == 0;
} // isFirstRow
/**
* Is Last Row - (zero based)
* @return true if last row
*/
public boolean isLastRow()
{
if (m_totalRows == 0)
return true;
return m_currentRow == m_totalRows-1;
} // isLastRow
/**
* Set Changed Column
* @param col column
* @param columnName column name
*/
public void setChangedColumn (int col, String columnName)
{
m_changedColumn = col;
m_columnName = columnName;
} // setChangedColumn
/**
* Get Changed Column
* @return changed column
*/
public int getChangedColumn()
{
return m_changedColumn;
} // getChangedColumn
/**
* Get Column Name
* @return column name
*/
public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Set Confirmed toggle
* @param confirmed confirmed
*/
public void setConfirmed (boolean confirmed)
{
m_confirmed = confirmed;
} // setConfirmed
/**
* Is Confirmed (e.g. user has seen it)
* @return true if confirmed
*/
public boolean isConfirmed()
{
return m_confirmed;
} // isConfirmed
} // DataStatusEvent

View File

@ -0,0 +1,34 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
/**
* Data Status Interface
*
* @author Jorg Janke
* @version $Id: DataStatusListener.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public interface DataStatusListener extends EventListener
{
/**
* Data Changed
* @param e event
*/
public void dataStatusChanged(DataStatusEvent e);
} // DataStatusListener

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,512 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.awt.*;
import java.io.*;
import java.rmi.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import org.apache.ecs.xhtml.*;
import org.compiere.db.*;
import org.compiere.plaf.*;
import org.compiere.util.*;
/**
* Window Model
*
* @author Jorg Janke
* @version $Id: GridWindow.java,v 1.4 2006/07/30 00:51:02 jjanke Exp $
*/
public class GridWindow implements Serializable
{
/**
* Get Grid Window
* @param ctx context
* @param WindowNo window no for ctx
* @param AD_Window_ID window id
* @return window or null if not found
*/
public static GridWindow get (Properties ctx, int WindowNo, int AD_Window_ID)
{
log.config("Window=" + WindowNo + ", AD_Window_ID=" + AD_Window_ID);
GridWindowVO mWindowVO = GridWindowVO.create (Env.getCtx(), WindowNo, AD_Window_ID);
if (mWindowVO == null)
return null;
return new GridWindow(mWindowVO);
} // get
/**************************************************************************
* Constructor
* @param vo value object
*/
public GridWindow (GridWindowVO vo)
{
m_vo = vo;
if (loadTabData())
enableEvents();
} // MWindow
/** Value Object */
private GridWindowVO m_vo;
/** Tabs */
private ArrayList<GridTab> m_tabs = new ArrayList<GridTab>();
/** Position */
private Rectangle m_position = null;
/** Model last updated */
private Timestamp m_modelUpdated = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(GridWindow.class);
/**************************************************************************
* Dispose
*/
public void dispose()
{
log.info("AD_Window_ID=" + m_vo.AD_Window_ID);
for (int i = 0; i < getTabCount(); i++)
getTab(i).dispose();
m_tabs.clear();
m_tabs = null;
} // dispose
/**
* Load is complete.
* Return when async load is complete
* Used for performance tests (Base.test())
*/
public void loadCompete ()
{
// for all tabs
for (int i = 0; i < getTabCount(); i++)
getTab(i).getMTable().loadComplete();
} // loadComplete
/**
* Get Tab data and create MTab(s)
* @return true if tab loaded
*/
private boolean loadTabData()
{
log.config("");
if (m_vo.Tabs == null)
return false;
for (int t = 0; t < m_vo.Tabs.size(); t++)
{
GridTabVO mTabVO = (GridTabVO)m_vo.Tabs.get(t);
if (mTabVO != null)
{
GridTab mTab = new GridTab(mTabVO);
Env.setContext(mTabVO.ctx, mTabVO.WindowNo, mTabVO.TabNo,
"KeyColumnName", mTab.getKeyColumnName());
// Set Link Column
if (mTab.getLinkColumnName().length() == 0)
{
ArrayList parents = mTab.getParentColumnNames();
// No Parent - no link
if (parents.size() == 0)
;
// Standard case
else if (parents.size() == 1)
mTab.setLinkColumnName((String)parents.get(0));
else
{
// More than one parent.
// Search prior tabs for the "right parent"
// for all previous tabs
for (int i = 0; i < m_tabs.size(); i++)
{
// we have a tab
GridTab tab = (GridTab)m_tabs.get(i);
String tabKey = tab.getKeyColumnName(); // may be ""
// look, if one of our parents is the key of that tab
for (int j = 0; j < parents.size(); j++)
{
String parent = (String)parents.get(j);
if (parent.equals(tabKey))
{
mTab.setLinkColumnName(parent);
break;
}
// The tab could have more than one key, look into their parents
if (tabKey.equals(""))
for (int k = 0; k < tab.getParentColumnNames().size(); k++)
if (parent.equals(tab.getParentColumnNames().get(k)))
{
mTab.setLinkColumnName(parent);
break;
}
} // for all parents
} // for all previous tabs
} // parents.size > 1
} // set Link column
mTab.setLinkColumnName(null); // overwrites, if AD_Column_ID exists
//
m_tabs.add(mTab);
}
} // for all tabs
return true;
} // loadTabData
/**
* Get Window Icon
* @return Icon for Window
*/
public Image getImage()
{
if (m_vo.AD_Image_ID == 0)
return null;
//
MImage mImage = MImage.get(Env.getCtx(), m_vo.AD_Image_ID);
return mImage.getImage();
} // getImage
/**
* Get Window Icon
* @return Icon for Window
*/
public Icon getIcon()
{
if (m_vo.AD_Image_ID == 0)
return null;
//
MImage mImage = MImage.get(Env.getCtx(), m_vo.AD_Image_ID);
return mImage.getIcon();
} // getIcon
/**
* Get Color
* @return AdempiereColor or null
*/
public AdempiereColor getColor()
{
if (m_vo.AD_Color_ID == 0)
return null;
MColor mc = new MColor(m_vo.ctx, m_vo.AD_Color_ID, null);
return mc.getAdempiereColor();
} // getColor
/**
* SO Trx Window
* @return true if SO Trx
*/
public boolean isSOTrx()
{
return m_vo.IsSOTrx;
} // isSOTrx
/**
* Open and query first Tab (events should be enabled) and get first row.
*/
public void query()
{
log.info("");
GridTab tab = getTab(0);
tab.query(false, 0, 0);
if (tab.getRowCount() > 0)
tab.navigate(0);
} // open
/**
* Enable Events - enable data events of tabs (add listeners)
*/
private void enableEvents()
{
for (int i = 0; i < getTabCount(); i++)
getTab(i).enableEvents();
} // enableEvents
/**
* Get number of Tabs
* @return number of tabs
*/
public int getTabCount()
{
return m_tabs.size();
} // getTabCount
/**
* Get i-th MTab - null if not valid
* @param i index
* @return MTab
*/
public GridTab getTab (int i)
{
if (i < 0 || i+1 > m_tabs.size())
return null;
return (GridTab)m_tabs.get(i);
} // getTab
/**
* Get Window_ID
* @return AD_Window_ID
*/
public int getAD_Window_ID()
{
return m_vo.AD_Window_ID;
} // getAD_Window_ID
/**
* Get WindowNo
* @return WindowNo
*/
public int getWindowNo()
{
return m_vo.WindowNo;
} // getWindowNo
/**
* Get Name
* @return name
*/
public String getName()
{
return m_vo.Name;
} // getName
/**
* Get Description
* @return Description
*/
public String getDescription()
{
return m_vo.Description;
} // getDescription
/**
* Get Help
* @return Help
*/
public String getHelp()
{
return m_vo.Help;
} // getHelp
/**
* Get Window Type
* @return Window Type see WindowType_*
*/
public String getWindowType()
{
return m_vo.WindowType;
} // getWindowType
/**
* Is Transaction Window
* @return true if transaction
*/
public boolean isTransaction()
{
return m_vo.WindowType.equals(GridWindowVO.WINDOWTYPE_TRX);
} // isTransaction
/**
* Get Window Size
* @return window size or null if not set
*/
public Dimension getWindowSize()
{
if (m_vo.WinWidth != 0 && m_vo.WinHeight != 0)
return new Dimension (m_vo.WinWidth, m_vo.WinHeight);
return null;
} // getWindowSize
/**
* To String
* @return String representation
*/
public String toString()
{
return "MWindow[" + m_vo.WindowNo + "," + m_vo.Name + " (" + m_vo.AD_Window_ID + ")]";
} // toString
/**
* Get Help HTML Document
* @param javaClient true if java client false for browser
* @return help
*/
public WebDoc getHelpDoc (boolean javaClient)
{
String title = Msg.getMsg(Env.getCtx(), "Window") + ": " + getName();
WebDoc doc = null;
if (javaClient)
{
doc = WebDoc.create (false, title, javaClient);
}
else // HTML
{
doc = WebDoc.createPopup (title);
doc.addPopupClose();
}
// body.addElement("&copy;&nbsp;Adempiere &nbsp; ");
// body.addElement(new a("http://www.adempiere.org/help/", "Online Help"));
td center = doc.addPopupCenter(false);
// Window
if (getDescription().length() != 0)
center.addElement(new p().addElement(new i(getDescription())));
if (getHelp().length() != 0)
center.addElement(new p().addElement(getHelp()));
// Links to Tabs
int size = getTabCount();
p p = new p();
for (int i = 0; i < size; i++)
{
GridTab tab = getTab(i);
if (i > 0)
p.addElement(" - ");
p.addElement(new a("#Tab"+i).addElement(tab.getName()));
}
center.addElement(p)
.addElement(new p().addElement(WebDoc.NBSP));
// For all Tabs
for (int i = 0; i < size; i++)
{
table table = new table("1", "5", "5", "100%", null);
GridTab tab = getTab(i);
tr tr = new tr()
.addElement(new th()
.addElement(new a().setName("Tab" + i)
.addElement(new h2(Msg.getMsg(Env.getCtx(), "Tab") + ": " + tab.getName()))));
if (tab.getDescription().length() != 0)
tr.addElement(new th()
.addElement(new i(tab.getDescription())));
else
tr.addElement(new th()
.addElement(WebDoc.NBSP));
table.addElement(tr);
// Desciption
td td = new td().setColSpan(2);
if (tab.getHelp().length() != 0)
td.addElement(new p().addElement(tab.getHelp()));
// Links to Fields
p = new p();
for (int j = 0; j < tab.getFieldCount(); j++)
{
GridField field = tab.getField(j);
String hdr = field.getHeader();
if (hdr != null && hdr.length() > 0)
{
if (j > 0)
p.addElement(" - ");
p.addElement(new a("#Field" + i + j, hdr));
}
}
td.addElement(p);
table.addElement(new tr().addElement(td));
// For all Fields
for (int j = 0; j < tab.getFieldCount(); j++)
{
GridField field = tab.getField(j);
String hdr = field.getHeader();
if (hdr != null && hdr.length() > 0)
{
td = new td().setColSpan(2)
.addElement(new a().setName("Field" + i + j)
.addElement(new h3(Msg.getMsg(Env.getCtx(), "Field") + ": " + hdr))
);
if (field.getDescription().length() != 0)
td.addElement(new i(field.getDescription()));
//
if (field.getHelp().length() != 0)
td.addElement(new p().addElement(field.getHelp()));
table.addElement(new tr().addElement(td));
}
} // for all Fields
center.addElement(table);
center.addElement(new p().addElement(WebDoc.NBSP));
} // for all Tabs
if (!javaClient)
doc.addPopupClose();
// System.out.println(doc.toString());
return doc;
} // getHelpDoc
/**
* Get Model last Updated
* @param recalc recalculate again
* @return date
*/
public Timestamp getModelUpdated (boolean recalc)
{
if (recalc || m_modelUpdated == null)
{
String sql = "SELECT MAX(w.Updated), MAX(t.Updated), MAX(tt.Updated), MAX(f.Updated), MAX(c.Updated) "
+ "FROM AD_Window w"
+ " INNER JOIN AD_Tab t ON (w.AD_Window_ID=t.AD_Window_ID)"
+ " INNER JOIN AD_Table tt ON (t.AD_Table_ID=tt.AD_Table_ID)"
+ " INNER JOIN AD_Field f ON (t.AD_Tab_ID=f.AD_Tab_ID)"
+ " INNER JOIN AD_Column c ON (f.AD_Column_ID=c.AD_Column_ID) "
+ "WHERE w.AD_Window_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_Window_ID());
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
{
m_modelUpdated = rs.getTimestamp(1); // Window
Timestamp ts = rs.getTimestamp(2); // Tab
if (ts.after(m_modelUpdated))
m_modelUpdated = ts;
ts = rs.getTimestamp(3); // Table
if (ts.after(m_modelUpdated))
m_modelUpdated = ts;
ts = rs.getTimestamp(4); // Field
if (ts.after(m_modelUpdated))
m_modelUpdated = ts;
ts = rs.getTimestamp(5); // Column
if (ts.after(m_modelUpdated))
m_modelUpdated = ts;
}
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;
}
}
return m_modelUpdated;
} // getModelUpdated
} // MWindow

View File

@ -0,0 +1,526 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.awt.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import org.compiere.util.*;
/**
* Window Workbench Model
*
* @author Jorg Janke
* @version $Id: GridWorkbench.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class GridWorkbench implements Serializable
{
/**
* Workbench Model Constructor
* @param ctx context
*/
public GridWorkbench (Properties ctx)
{
m_ctx = ctx;
} // MWorkbench
/**
* No Workbench - Just Frame for Window
* @param ctx context
* @param AD_Window_ID window
*/
public GridWorkbench (Properties ctx, int AD_Window_ID)
{
m_ctx = ctx;
m_windows.add (new WBWindow(TYPE_WINDOW, AD_Window_ID));
} // MWorkbench
/** Properties */
private Properties m_ctx;
/** List of windows */
private ArrayList<WBWindow> m_windows = new ArrayList<WBWindow>();
private int AD_Workbench_ID = 0;
private String Name = "";
private String Description = "";
private String Help = "";
private int AD_Column_ID = 0;
private int AD_Image_ID = 0;
private int AD_Color_ID = 0;
private int PA_Goal_ID = 0;
private String ColumnName = "";
/** Logger */
private static CLogger log = CLogger.getCLogger(GridWorkbench.class);
/**
* Init Workbench
* @param ad_Workbench_ID workbench
* @return true if initialized
*/
public boolean initWorkbench (int ad_Workbench_ID)
{
AD_Workbench_ID = ad_Workbench_ID;
// Get WB info
String sql = null;
if (Env.isBaseLanguage(m_ctx, "AD_Workbench"))
sql = "SELECT w.Name,w.Description,w.Help," // 1..3
+ " w.AD_Column_ID,w.AD_Image_ID,w.AD_Color_ID,w.PA_Goal_ID," // 4..7
+ " c.ColumnName " // 8
+ "FROM AD_Workbench w, AD_Column c "
+ "WHERE w.AD_Workbench_ID=?" // #1
+ " AND w.IsActive='Y'"
+ " AND w.AD_Column_ID=c.AD_Column_ID";
else
sql = "SELECT t.Name,t.Description,t.Help,"
+ " w.AD_Column_ID,w.AD_Image_ID,w.AD_Color_ID,w.PA_Goal_ID,"
+ " c.ColumnName "
+ "FROM AD_Workbench w, AD_Workbench_Trl t, AD_Column c "
+ "WHERE w.AD_Workbench_ID=?" // #1
+ " AND w.IsActive='Y'"
+ " AND w.AD_Workbench_ID=t.AD_Workbench_ID"
+ " AND t.AD_Language='" + Env.getAD_Language(m_ctx) + "'"
+ " AND w.AD_Column_ID=c.AD_Column_ID";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Workbench_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
Name = rs.getString(1);
Description = rs.getString(2);
if (Description == null)
Description = "";
Help = rs.getString(3);
if (Help == null)
Help = "";
//
AD_Column_ID = rs.getInt(4);
AD_Image_ID = rs.getInt(5);
AD_Color_ID = rs.getInt(6);
PA_Goal_ID = rs.getInt(7);
ColumnName = rs.getString(8);
}
else
AD_Workbench_ID = 0;
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (AD_Workbench_ID == 0)
return false;
return initWorkbenchWindows();
} // initWorkbench
/**
* String Representation
* @return info
*/
public String toString()
{
return "MWorkbench ID=" + AD_Workbench_ID + " " + Name
+ ", windows=" + m_windows.size() + ", LinkColumn=" + ColumnName;
} // toString
/**
* Dispose
*/
public void dispose()
{
for (int i = 0; i < m_windows.size(); i++)
{
dispose(i);
}
m_windows.clear();
m_windows = null;
} // dispose
/**
* Get Workbench Query.
* @return ColumnName=@#ColumnName@
*/
public MQuery getQuery()
{
return MQuery.getEqualQuery(ColumnName, "@#" + ColumnName + "@");
} // getQuery
/*************************************************************************/
/**
* Get Workbench
* @return workbensch id
*/
public int getAD_Workbench_ID()
{
return AD_Workbench_ID;
}
/**
* Get Name
* @return name
*/
public String getName()
{
return Name;
}
/**
* Get Description
* @return description
*/
public String getDescription()
{
return Description;
}
/**
* Get Help
* @return help
*/
public String getHelp()
{
return Help;
}
/**
* Get Link AD_Column_ID
* @return column
*/
public int getAD_Column_ID()
{
return AD_Column_ID;
}
/**
* Get AD_Image_ID
* @return image
*/
public int getAD_Image_ID()
{
return AD_Image_ID;
}
/**
* Get AD_Color_ID
* @return color
*/
public int getAD_Color_ID()
{
return AD_Color_ID;
}
/**
* Get PA_Goal_ID
* @return goal
*/
public int getPA_Goal_ID()
{
return PA_Goal_ID;
}
/*************************************************************************/
/** Window */
public static final int TYPE_WINDOW = 1;
/** Form */
public static final int TYPE_FORM = 2;
/** Process */
public static final int TYPE_PROCESS = 3;
/** Task */
public static final int TYPE_TASK = 4;
/**
* Init Workbench Windows
* @return true if init ok
*/
private boolean initWorkbenchWindows()
{
String sql = "SELECT AD_Window_ID, AD_Form_ID, AD_Process_ID, AD_Task_ID "
+ "FROM AD_WorkbenchWindow "
+ "WHERE AD_Workbench_ID=? AND IsActive='Y'"
+ "ORDER BY SeqNo";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Workbench_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
int AD_Window_ID = rs.getInt(1);
int AD_Form_ID = rs.getInt(2);
int AD_Process_ID = rs.getInt(3);
int AD_Task_ID = rs.getInt(4);
//
if (AD_Window_ID > 0)
m_windows.add (new WBWindow(TYPE_WINDOW, AD_Window_ID));
else if (AD_Form_ID > 0)
m_windows.add (new WBWindow(TYPE_FORM, AD_Form_ID));
else if (AD_Process_ID > 0)
m_windows.add (new WBWindow(TYPE_PROCESS, AD_Process_ID));
else if (AD_Task_ID > 0)
m_windows.add (new WBWindow(TYPE_TASK, AD_Task_ID));
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return false;
}
return true;
} // initWorkbenchWindows
/**
* Get Window Count
* @return window count
*/
public int getWindowCount()
{
return m_windows.size();
} // getWindowCount
/**
* Get Window Type of Window
* @param index index in workbench
* @return -1 if not valid
*/
public int getWindowType (int index)
{
if (index < 0 || index > m_windows.size())
return -1;
WBWindow win = (WBWindow)m_windows.get(index);
return win.Type;
} // getWindowType
/**
* Get ID for Window
* @param index index in workbench
* @return -1 if not valid
*/
public int getWindowID (int index)
{
if (index < 0 || index > m_windows.size())
return -1;
WBWindow win = (WBWindow)m_windows.get(index);
return win.ID;
} // getWindowID
/**************************************************************************
* Set Window Model of Window
* @param index index in workbench
* @param mw model window
*/
public void setMWindow (int index, GridWindow mw)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.Type != TYPE_WINDOW)
throw new IllegalArgumentException ("Not a MWindow: " + index);
win.mWindow = mw;
} // setMWindow
/**
* Get Window Model of Window
* @param index index in workbench
* @return model window
*/
public GridWindow getMWindow (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.Type != TYPE_WINDOW)
throw new IllegalArgumentException ("Not a MWindow: " + index);
return win.mWindow;
} // getMWindow
/**
* Get Name of Window
* @param index index in workbench
* @return Window Name or null if not set
*/
public String getName (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null && win.Type == TYPE_WINDOW)
return win.mWindow.getName();
return null;
} // getName
/**
* Get Description of Window
* @param index index in workbench
* @return Window Description or null if not set
*/
public String getDescription (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null && win.Type == TYPE_WINDOW)
return win.mWindow.getDescription();
return null;
} // getDescription
/**
* Get Help of Window
* @param index index in workbench
* @return Window Help or null if not set
*/
public String getHelp (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null && win.Type == TYPE_WINDOW)
return win.mWindow.getHelp();
return null;
} // getHelp
/**
* Get Icon of Window
* @param index index in workbench
* @return Window Icon or null if not set
*/
public Icon getIcon (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null && win.Type == TYPE_WINDOW)
return win.mWindow.getIcon();
return null;
} // getIcon
/**
* Get Image Icon of Window
* @param index index in workbench
* @return Window Icon or null if not set
*/
public Image getImage (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null && win.Type == TYPE_WINDOW)
return win.mWindow.getImage();
return null;
} // getImage
/**
* Get AD_Color_ID of Window
* @param index index in workbench
* @return Window Color or Workbench color if not set
*/
public int getAD_Color_ID (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
int retValue = -1;
// if (win.mWindow != null && win.Type == TYPE_WINDOW)
// return win.mWindow.getAD_Color_ID();
if (retValue == -1)
return getAD_Color_ID();
return retValue;
} // getAD_Color_ID
/**
* Set WindowNo of Window
* @param index index in workbench
* @param windowNo window no
*/
public void setWindowNo (int index, int windowNo)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
win.WindowNo = windowNo;
} // getWindowNo
/**
* Get WindowNo of Window
* @param index index in workbench
* @return WindowNo of Window if previously set, otherwise -1;
*/
public int getWindowNo (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
return win.WindowNo;
} // getWindowNo
/**
* Dispose of Window
* @param index index in workbench
*/
public void dispose (int index)
{
if (index < 0 || index > m_windows.size())
throw new IllegalArgumentException ("Index invalid: " + index);
WBWindow win = (WBWindow)m_windows.get(index);
if (win.mWindow != null)
win.mWindow.dispose();
win.mWindow = null;
} // dispose
/**
* Get Window Size
* @return window size or null if not set
*/
public Dimension getWindowSize()
{
return null;
} // getWindowSize
/**************************************************************************
* Window Type
*/
class WBWindow
{
/**
* WBWindow
* @param type
* @param id
*/
public WBWindow (int type, int id)
{
Type = type;
ID = id;
}
/** Type */
public int Type = 0;
/** ID */
public int ID = 0;
/** Window No */
public int WindowNo = -1;
/** Window Midel */
public GridWindow mWindow = null;
// public MFrame mFrame = null;
// public MProcess mProcess = null;
} // WBWindow
} // Workbench

View File

@ -0,0 +1,83 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Media Access Profile
*
* @author Jorg Janke
* @version $Id: MAccessProfile.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAccessProfile extends X_CM_AccessProfile
{
/**
* Access to Container
* @param ctx context
* @param CM_Container_ID
* @param AD_User_ID user to check
* @return true if access to container
*/
public static boolean isAccessContainer (Properties ctx, int CM_Container_ID,
int AD_User_ID)
{
// NIT
return true;
} // isAccessContainer
/**
* Access to Container
* @param ctx context
* @param CM_Container_ID
* @param AD_Role_ID 0 or role to checl
* @param C_BPGroup_ID 0 or bpartner to check
* @return true if access to container
*/
public static boolean isAccessContainer (Properties ctx, int CM_Container_ID,
int AD_Role_ID, int C_BPGroup_ID)
{
// NIT
return true;
} // isAccessContainer
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param CM_AccessProfile_ID id
* @param trxName transaction
*/
public MAccessProfile (Properties ctx, int CM_AccessProfile_ID,
String trxName)
{
super (ctx, CM_AccessProfile_ID, trxName);
} // MAccessProfile
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAccessProfile (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MAccessProfile
} // MAccessProfile

View File

@ -0,0 +1,201 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Accounting Processor Model
*
* @author Jorg Janke
* @version $Id: MAcctProcessor.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAcctProcessor extends X_C_AcctProcessor
implements AdempiereProcessor
{
/**
* Get Active
* @param ctx context
* @return active processors
*/
public static MAcctProcessor[] getActive (Properties ctx)
{
ArrayList<MAcctProcessor> list = new ArrayList<MAcctProcessor>();
String sql = "SELECT * FROM C_AcctProcessor WHERE IsActive='Y'";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAcctProcessor (ctx, rs, null));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, "getActive", e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MAcctProcessor[] retValue = new MAcctProcessor[list.size ()];
list.toArray (retValue);
return retValue;
} // getActive
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MAcctProcessor.class);
/**
* Standard Construvtor
* @param ctx context
* @param C_AcctProcessor_ID id
* @param trxName transaction
*/
public MAcctProcessor (Properties ctx, int C_AcctProcessor_ID, String trxName)
{
super (ctx, C_AcctProcessor_ID, trxName);
if (C_AcctProcessor_ID == 0)
{
// setName (null);
// setSupervisor_ID (0);
setFrequencyType (FREQUENCYTYPE_Hour);
setFrequency (1);
setKeepLogDays (7); // 7
}
} // MAcctProcessor
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAcctProcessor (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAcctProcessor
/**
* Parent Constructor
* @param client parent
* @param Supervisor_ID admin
*/
public MAcctProcessor (MClient client, int Supervisor_ID)
{
this (client.getCtx(), 0, client.get_TrxName());
setClientOrg(client);
setName (client.getName() + " - "
+ Msg.translate(getCtx(), "C_AcctProcessor_ID"));
setSupervisor_ID (Supervisor_ID);
} // MAcctProcessor
/**
* Get Server ID
* @return id
*/
public String getServerID ()
{
return "AcctProcessor" + get_ID();
} // getServerID
/**
* 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<MAcctProcessorLog> list = new ArrayList<MAcctProcessorLog>();
String sql = "SELECT * "
+ "FROM C_AcctProcessorLog "
+ "WHERE C_AcctProcessor_ID=? "
+ "ORDER BY Created DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_AcctProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAcctProcessorLog (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;
}
MAcctProcessorLog[] retValue = new MAcctProcessorLog[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 C_AcctProcessorLog "
+ "WHERE C_AcctProcessor_ID=" + getC_AcctProcessor_ID()
+ " AND (Created+" + getKeepLogDays() + ") < SysDate";
int no = DB.executeUpdate(sql, get_TrxName());
return 0;
} // deleteLog
} // MAcctProcessor

View File

@ -0,0 +1,68 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Accounting Processor Log
*
* @author Jorg Janke
* @version $Id: MAcctProcessorLog.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAcctProcessorLog extends X_C_AcctProcessorLog
implements AdempiereProcessorLog
{
/**
* Standard Constructor
* @param ctx context
* @param C_AcctProcessorLog_ID id
* @param trxName transaction
*/
public MAcctProcessorLog (Properties ctx, int C_AcctProcessorLog_ID, String trxName)
{
super (ctx, C_AcctProcessorLog_ID, trxName);
} // MAcctProcessorLog
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAcctProcessorLog (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAcctProcessorLog
/**
* Parent Constructor
* @param parent parent
* @param summary summary
*/
public MAcctProcessorLog (MAcctProcessor parent, String summary)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setC_AcctProcessor_ID(parent.getC_AcctProcessor_ID());
setSummary(summary);
} // MAcctProcessorLog
} // MAcctProcessorLog

View File

@ -0,0 +1,174 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Performance Achievement
*
* @author Jorg Janke
* @version $Id: MAchievement.java,v 1.2 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAchievement extends X_PA_Achievement
{
/**
* Get achieved Achievements Of Measure
* @param measure Measure
* @return array of Achievements
*/
public static MAchievement[] get (MMeasure measure)
{
return getOfMeasure(measure.getCtx(), measure.getPA_Measure_ID());
} // get
/**
* Get achieved Achievements Of Measure
* @param ctx context
* @param PA_Measure_ID measure id
* @return array of Achievements
*/
public static MAchievement[] getOfMeasure (Properties ctx, int PA_Measure_ID)
{
ArrayList<MAchievement> list = new ArrayList<MAchievement>();
String sql = "SELECT * FROM PA_Achievement "
+ "WHERE PA_Measure_ID=? AND IsAchieved='Y' ORDER BY SeqNo, DateDoc";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, PA_Measure_ID);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAchievement (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;
}
//
MAchievement[] retValue = new MAchievement[list.size ()];
list.toArray (retValue);
return retValue;
} // getOfMeasure
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MAchievement.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param PA_Achievement_ID id
* @param trxName trx
*/
public MAchievement (Properties ctx, int PA_Achievement_ID, String trxName)
{
super (ctx, PA_Achievement_ID, trxName);
} // MAchievement
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MAchievement (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MAchievement
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAchievement[");
sb.append (get_ID()).append ("-").append (getName()).append ("]");
return sb.toString ();
} // toString
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (isAchieved())
{
if (getManualActual().signum() == 0)
setManualActual(Env.ONE);
if (getDateDoc() == null)
setDateDoc(new Timestamp(System.currentTimeMillis()));
}
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (success)
updateAchievementGoals();
return success;
} // afterSave
/**
* After Delete
* @param success success
* @return success
*/
protected boolean afterDelete (boolean success)
{
if (success)
updateAchievementGoals();
return success;
} // afterDelete
/**
* Update Goals with Achievement
*/
private void updateAchievementGoals()
{
MMeasure measure = MMeasure.get (getCtx(), getPA_Measure_ID());
measure.updateGoals();
} // updateAchievementGoals
} // MAchievement

View File

@ -0,0 +1,87 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Activity Model
*
* @author Jorg Janke
* @version $Id: MActivity.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/
public class MActivity extends X_C_Activity
{
/**
* Standard Constructor
* @param ctx context
* @param C_Activity_ID id
* @param trxName transaction
*/
public MActivity (Properties ctx, int C_Activity_ID, String trxName)
{
super (ctx, C_Activity_ID, trxName);
} // MActivity
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MActivity (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MActivity
/**
* After Save.
* Insert
* - create tree
* @param newRecord insert
* @param success save success
* @return true if saved
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (newRecord)
insert_Tree(MTree_Base.TREETYPE_Activity);
// Value/Name change
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
MAccount.updateValueDescription(getCtx(), "C_Activity_ID=" + getC_Activity_ID(), get_TrxName());
return true;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
protected boolean afterDelete (boolean success)
{
if (success)
delete_Tree(MTree_Base.TREETYPE_Activity);
return success;
} // afterDelete
} // MActivity

View File

@ -0,0 +1,96 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
import javax.servlet.http.*;
/**
* Container Model
*
* @author Yves Sandfort
* @version $Id$
*/
@SuppressWarnings("serial")
public class MAd extends X_CM_Ad
{
/**
* Standard constructor for AD
* @param ctx Context
* @param CM_Ad_ID ID
* @param trxName Transaction
*/
public MAd (Properties ctx, int CM_Ad_ID, String trxName)
{
super (ctx, CM_Ad_ID, trxName);
}
/**
* Get's the relevant current Impression value which is Actual+Start
* @return int
*/
public int getCurrentImpression() {
return getActualImpression() + getStartImpression();
}
/**
* Adds an Impression to the current Ad
* We will deactivate the Ad as soon as one of the Max Criterias are fullfiled
*/
public void addImpression() {
setActualImpression(getActualImpression()+1);
if (getCurrentImpression()>=getMaxImpression())
setIsActive(false);
save();
}
/**
* Get Next of this Category, this Procedure will return the next Ad in a category and expire it if needed
* @param ctx Context
* @param CM_Ad_Cat_ID Category
* @param trxName Transaction
* @return MAd
*/
public static MAd getNext(Properties ctx, int CM_Ad_Cat_ID, String trxName) {
MAd thisAd = null;
int [] thisAds = MAd.getAllIDs("CM_Ad","ActualImpression+StartImpression<MaxImpression AND CM_Ad_Cat_ID=" + CM_Ad_Cat_ID, trxName);
if (thisAds!=null) {
for (int i=0;i<thisAds.length;i++) {
MAd tempAd = new MAd(ctx, thisAds[i], trxName);
if (thisAd==null)
thisAd = tempAd;
if (tempAd.getCurrentImpression()<=thisAd.getCurrentImpression())
thisAd = tempAd;
}
}
if (thisAd!=null)
thisAd.addImpression();
return thisAd;
}
/**
* Add Click Record to Log
* @param request ServletReqeust
*/
public void addClick(HttpServletRequest request) {
setActualClick(getActualClick()+1);
if (getActualClick()>getMaxClick())
setIsActive(true);
save();
}
} // MAd

View File

@ -0,0 +1,155 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Advertisement Model
*
* @author Jorg Janke
* @version $Id: MAdvertisement.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAdvertisement extends X_W_Advertisement
{
/**
* Default Constructor
* @param ctx context
* @param W_Advertisement_ID id
* @param trxName transaction
*/
public MAdvertisement (Properties ctx, int W_Advertisement_ID, String trxName)
{
super (ctx, W_Advertisement_ID, trxName);
/** if (W_Advertisement_ID == 0)
{
setC_BPartner_ID (0);
setIsSelfService (false);
setName (null);
setW_Advertisement_ID (0);
}
**/
} // MAdvertisement
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAdvertisement (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAdvertisement
/** Click Count */
private MClickCount m_clickCount = null;
/** Counter Count */
private MCounterCount m_counterCount = null;
/** Sales Rep */
private int m_SalesRep_ID = 0;
/**************************************************************************
* Get ClickCount
* @return Click Count
*/
public MClickCount getMClickCount()
{
if (getW_ClickCount_ID() == 0)
return null;
if (m_clickCount == null)
m_clickCount = new MClickCount (getCtx(), getW_ClickCount_ID(), get_TrxName());
return m_clickCount;
} // MClickCount
/**
* Get Click Target URL (from ClickCount)
* @return URL
*/
public String getClickTargetURL()
{
getMClickCount();
if (m_clickCount == null)
return "-";
return m_clickCount.getTargetURL();
} // getClickTargetURL
/**
* Set Click Target URL (in ClickCount)
* @param TargetURL url
*/
public void setClickTargetURL(String TargetURL)
{
getMClickCount();
if (m_clickCount == null)
m_clickCount = new MClickCount(this);
if (m_clickCount != null)
{
m_clickCount.setTargetURL(TargetURL);
m_clickCount.save(get_TrxName());
}
} // getClickTargetURL
/**
* Get Weekly Count
* @return weekly count
*/
public ValueNamePair[] getClickCountWeek ()
{
getMClickCount();
if (m_clickCount == null)
return new ValueNamePair[0];
return m_clickCount.getCountWeek();
} // getClickCountWeek
/**
* Get CounterCount
* @return Counter Count
*/
public MCounterCount getMCounterCount()
{
if (getW_CounterCount_ID() == 0)
return null;
if (m_counterCount == null)
m_counterCount = new MCounterCount (getCtx(), getW_CounterCount_ID(), get_TrxName());
return m_counterCount;
} // MCounterCount
/**
* Get Sales Rep ID.
* (AD_User_ID of oldest BP user)
* @return Sales Rep ID
*/
public int getSalesRep_ID()
{
if (m_SalesRep_ID == 0)
{
m_SalesRep_ID = getAD_User_ID();
if (m_SalesRep_ID == 0)
m_SalesRep_ID = DB.getSQLValue(null,
"SELECT AD_User_ID FROM AD_User "
+ "WHERE C_BPartner_ID=? AND IsActive='Y' ORDER BY 1", getC_BPartner_ID());
}
return m_SalesRep_ID;
} // getSalesRep_ID
} // MAdvertisement

View File

@ -0,0 +1,237 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Aging Model
*
* @author Jorg Janke
* @version $Id: MAging.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAging extends X_T_Aging
{
/**
* Standard Constructor
* @param ctx context
* @param T_Aging_ID id
* @param trxName transaction
*/
public MAging (Properties ctx, int T_Aging_ID, String trxName)
{
super (ctx, T_Aging_ID, trxName);
if (T_Aging_ID == 0)
{
// setAD_PInstance_ID (0);
// setC_BP_Group_ID (0);
// setC_BPartner_ID (0);
// setC_Currency_ID (0);
//
setDueAmt (Env.ZERO);
setDue0 (Env.ZERO);
setDue0_7 (Env.ZERO);
setDue0_30 (Env.ZERO);
setDue1_7 (Env.ZERO);
setDue31_60 (Env.ZERO);
setDue31_Plus (Env.ZERO);
setDue61_90 (Env.ZERO);
setDue61_Plus (Env.ZERO);
setDue8_30 (Env.ZERO);
setDue91_Plus (Env.ZERO);
//
setPastDueAmt (Env.ZERO);
setPastDue1_7 (Env.ZERO);
setPastDue1_30 (Env.ZERO);
setPastDue31_60 (Env.ZERO);
setPastDue31_Plus (Env.ZERO);
setPastDue61_90 (Env.ZERO);
setPastDue61_Plus (Env.ZERO);
setPastDue8_30 (Env.ZERO);
setPastDue91_Plus (Env.ZERO);
//
setOpenAmt(Env.ZERO);
setInvoicedAmt(Env.ZERO);
//
setIsListInvoices (false);
setIsSOTrx (false);
// setDueDate (new Timestamp(System.currentTimeMillis()));
// setStatementDate (new Timestamp(System.currentTimeMillis()));
}
} // T_Aging
/**
* Full Constructor
* @param ctx context
* @param AD_PInstance_ID instance
* @param StatementDate statement date
* @param C_BPartner_ID bpartner
* @param C_Currency_ID currency
* @param C_Invoice_ID invoice
* @param C_InvoicePaySchedule_ID invoice schedule
* @param C_BP_Group_ID group
* @param DueDate due date
* @param IsSOTrx SO Trx
* @param trxName transaction
*/
public MAging (Properties ctx, int AD_PInstance_ID, Timestamp StatementDate,
int C_BPartner_ID, int C_Currency_ID,
int C_Invoice_ID, int C_InvoicePaySchedule_ID,
int C_BP_Group_ID, Timestamp DueDate, boolean IsSOTrx, String trxName)
{
this (ctx, 0, trxName);
setAD_PInstance_ID (AD_PInstance_ID);
setStatementDate(StatementDate);
//
setC_BPartner_ID (C_BPartner_ID);
setC_Currency_ID (C_Currency_ID);
setC_BP_Group_ID (C_BP_Group_ID);
setIsSOTrx (IsSOTrx);
// Optional
// setC_Invoice_ID (C_Invoice_ID); // may be zero
set_ValueNoCheck ("C_Invoice_ID", new Integer(C_Invoice_ID));
// setC_InvoicePaySchedule_ID(C_InvoicePaySchedule_ID); // may be zero
set_Value ("C_InvoicePaySchedule_ID", new Integer(C_InvoicePaySchedule_ID));
setIsListInvoices(C_Invoice_ID != 0);
//
setDueDate(DueDate); // only sensible if List invoices
} // MAging
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAging (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAging
/** Number of items */
private int m_noItems = 0;
/** Sum of Due Days */
private int m_daysDueSum = 0;
/**
* Add Amount to Buckets
* @param DueDate due date
* @param daysDue positive due - negative not due
* @param invoicedAmt invoiced amount
* @param openAmt open amount
*/
public void add (Timestamp DueDate, int daysDue, BigDecimal invoicedAmt, BigDecimal openAmt)
{
if (invoicedAmt == null)
invoicedAmt = Env.ZERO;
setInvoicedAmt(getInvoicedAmt().add(invoicedAmt));
if (openAmt == null)
openAmt = Env.ZERO;
setOpenAmt(getOpenAmt().add(openAmt));
// Days Due
m_noItems++;
m_daysDueSum += daysDue;
setDaysDue(m_daysDueSum/m_noItems);
// Due Date
if (getDueDate().after(DueDate))
setDueDate(DueDate); // earliest
//
BigDecimal amt = openAmt;
// Not due - negative
if (daysDue <= 0)
{
setDueAmt (getDueAmt().add(amt));
if (daysDue == 0)
setDue0 (getDue0().add(amt));
if (daysDue >= -7)
setDue0_7 (getDue0_7().add(amt));
if (daysDue >= -30)
setDue0_30 (getDue0_30().add(amt));
if (daysDue <= -1 && daysDue >= -7)
setDue1_7 (getDue1_7().add(amt));
if (daysDue <= -8 && daysDue >= -30)
setDue8_30 (getDue8_30().add(amt));
if (daysDue <= -31 && daysDue >= -60)
setDue31_60 (getDue31_60().add(amt));
if (daysDue <= -31)
setDue31_Plus (getDue31_Plus().add(amt));
if (daysDue <= -61 && daysDue >= -90)
setDue61_90 (getDue61_90().add(amt));
if (daysDue <= -61)
setDue61_Plus (getDue61_Plus().add(amt));
if (daysDue <= -91)
setDue91_Plus (getDue91_Plus().add(amt));
}
else // Due = positive (> 1)
{
setPastDueAmt (getPastDueAmt().add(amt));
if (daysDue <= 7)
setPastDue1_7 (getPastDue1_7().add(amt));
if (daysDue <= 30)
setPastDue1_30 (getPastDue1_30().add(amt));
if (daysDue >= 8 && daysDue <= 30)
setPastDue8_30 (getPastDue8_30().add(amt));
if (daysDue >= 31 && daysDue <= 60)
setPastDue31_60 (getPastDue31_60().add(amt));
if (daysDue >= 31)
setPastDue31_Plus (getPastDue31_Plus().add(amt));
if (daysDue >= 61 && daysDue <= 90)
setPastDue61_90 (getPastDue61_90().add(amt));
if (daysDue >= 61)
setPastDue61_Plus (getPastDue61_Plus().add(amt));
if (daysDue >= 91)
setPastDue91_Plus (getPastDue91_Plus().add(amt));
}
} // add
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("MAging[");
sb.append("AD_PInstance_ID=").append(getAD_PInstance_ID())
.append(",C_BPartner_ID=").append(getC_BPartner_ID())
.append(",C_Currency_ID=").append(getC_Currency_ID())
.append(",C_Invoice_ID=").append(getC_Invoice_ID());
sb.append("]");
return sb.toString();
} // toString
} // MAging

View File

@ -0,0 +1,226 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Alert Model
*
* @author Jorg Janke
* @version $Id: MAlert.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MAlert extends X_AD_Alert
{
/**
* Standard Constructor
* @param ctx context
* @param AD_Alert_ID id
* @param trxName transaction
*/
public MAlert (Properties ctx, int AD_Alert_ID, String trxName)
{
super (ctx, AD_Alert_ID, trxName);
if (AD_Alert_ID == 0)
{
// setAD_AlertProcessor_ID (0);
// setName (null);
// setAlertMessage (null);
// setAlertSubject (null);
setEnforceClientSecurity (true); // Y
setEnforceRoleSecurity (true); // Y
setIsValid (true); // Y
}
} // MAlert
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlert (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAlert
/** The Rules */
private MAlertRule[] m_rules = null;
/** The Recipients */
private MAlertRecipient[] m_recipients = null;
/**
* Get Rules
* @param reload reload data
* @return array of rules
*/
public MAlertRule[] getRules (boolean reload)
{
if (m_rules != null && !reload)
return m_rules;
String sql = "SELECT * FROM AD_AlertRule "
+ "WHERE AD_Alert_ID=?";
ArrayList<MAlertRule> list = new ArrayList<MAlertRule>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_Alert_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlertRule (getCtx(), 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;
}
//
m_rules = new MAlertRule[list.size ()];
list.toArray (m_rules);
return m_rules;
} // getRules
/**
* Get Recipients
* @param reload reload data
* @return array of recipients
*/
public MAlertRecipient[] getRecipients (boolean reload)
{
if (m_recipients != null && !reload)
return m_recipients;
String sql = "SELECT * FROM AD_AlertRecipient "
+ "WHERE AD_Alert_ID=?";
ArrayList<MAlertRecipient> list = new ArrayList<MAlertRecipient>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_Alert_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlertRecipient (getCtx(), 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;
}
//
m_recipients = new MAlertRecipient[list.size ()];
list.toArray (m_recipients);
return m_recipients;
} // getRecipients
/**
* Get First Role if exist
* @return AD_Role_ID or -1
*/
public int getFirstAD_Role_ID()
{
getRecipients(false);
for (int i = 0; i < m_recipients.length; i++)
{
if (m_recipients[i].getAD_Role_ID() != -1)
return m_recipients[i].getAD_Role_ID();
}
return -1;
} // getForstAD_Role_ID
/**
* Get First User Role if exist
* @return AD_Role_ID or -1
*/
public int getFirstUserAD_Role_ID()
{
getRecipients(false);
int AD_User_ID = getFirstAD_User_ID();
if (AD_User_ID != -1)
{
MUserRoles[] urs = MUserRoles.getOfUser(getCtx(), AD_User_ID);
for (int i = 0; i < urs.length; i++)
{
if (urs[i].isActive())
return urs[i].getAD_Role_ID();
}
}
return -1;
} // getFirstUserAD_Role_ID
/**
* Get First User if exist
* @return AD_User_ID or -1
*/
public int getFirstAD_User_ID()
{
getRecipients(false);
for (int i = 0; i < m_recipients.length; i++)
{
if (m_recipients[i].getAD_User_ID() != -1)
return m_recipients[i].getAD_User_ID();
}
return -1;
} // getFirstAD_User_ID
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlert[");
sb.append(get_ID())
.append("-").append(getName())
.append(",Valid=").append(isValid());
if (m_rules != null)
sb.append(",Rules=").append(m_rules.length);
if (m_recipients != null)
sb.append(",Recipients=").append(m_recipients.length);
sb.append ("]");
return sb.toString ();
} // toString
} // MAlert

View File

@ -0,0 +1,225 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Alert Processor
*
* @author Jorg Janke
* @version $Id: MAlertProcessor.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAlertProcessor extends X_AD_AlertProcessor
implements AdempiereProcessor
{
/**
* Get Active
* @param ctx context
* @return active processors
*/
public static MAlertProcessor[] getActive (Properties ctx)
{
ArrayList<MAlertProcessor> list = new ArrayList<MAlertProcessor>();
String sql = "SELECT * FROM AD_AlertProcessor WHERE IsActive='Y'";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlertProcessor (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;
}
MAlertProcessor[] retValue = new MAlertProcessor[list.size ()];
list.toArray (retValue);
return retValue;
} // getActive
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MAlertProcessor.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param AD_AlertProcessorLog_ID id
* @param trxName transaction
*/
public MAlertProcessor (Properties ctx, int AD_AlertProcessorLog_ID, String trxName)
{
super (ctx, AD_AlertProcessorLog_ID, trxName);
} // MAlertProcessor
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlertProcessor (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAlertProcessor
/** The Alerts */
private MAlert[] m_alerts = null;
/**
* Get Server ID
* @return id
*/
public String getServerID ()
{
return "AlertProcessor" + get_ID();
} // getServerID
/**
* 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<MAlertProcessorLog> list = new ArrayList<MAlertProcessorLog>();
String sql = "SELECT * "
+ "FROM AD_AlertProcessorLog "
+ "WHERE AD_AlertProcessor_ID=? "
+ "ORDER BY Created DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_AlertProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlertProcessorLog (getCtx(), 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;
}
MAlertProcessorLog[] retValue = new MAlertProcessorLog[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_AlertProcessorLog "
+ "WHERE AD_AlertProcessor_ID=" + getAD_AlertProcessor_ID()
+ " AND (Created+" + getKeepLogDays() + ") < SysDate";
int no = DB.executeUpdate(sql, get_TrxName());
return 0;
} // deleteLog
/**
* Get Alerts
* @param reload reload data
* @return array of alerts
*/
public MAlert[] getAlerts (boolean reload)
{
if (m_alerts != null && !reload)
return m_alerts;
String sql = "SELECT * FROM AD_Alert "
+ "WHERE AD_AlertProcessor_ID=?";
ArrayList<MAlert> list = new ArrayList<MAlert>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getAD_AlertProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAlert (getCtx(), 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;
}
//
m_alerts = new MAlert[list.size ()];
list.toArray (m_alerts);
return m_alerts;
} // getAlerts
} // MAlertProcessor

View File

@ -0,0 +1,67 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Alert Log
*
* @author Jorg Janke
* @version $Id: MAlertProcessorLog.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MAlertProcessorLog extends X_AD_AlertProcessorLog
implements AdempiereProcessorLog
{
/**
* Standard Constructor
* @param ctx context
* @param AD_AlertProcessorLog_ID id
* @param trxName transaction
*/
public MAlertProcessorLog (Properties ctx, int AD_AlertProcessorLog_ID, String trxName)
{
super (ctx, AD_AlertProcessorLog_ID, trxName);
} // MAlertProcessorLog
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlertProcessorLog (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAlertProcessorLog
/**
* Parent Constructor
* @param parent parent
* @param summary summary
*/
public MAlertProcessorLog (MAlertProcessor parent, String summary)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setAD_AlertProcessor_ID(parent.getAD_AlertProcessor_ID());
setSummary(summary);
} // MAlertProcessorLog
} // MAlertProcessorLog

View File

@ -0,0 +1,94 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Alert Recipient
*
* @author Jorg Janke
* @version $Id: MAlertRecipient.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAlertRecipient extends X_AD_AlertRecipient
{
/**
* Standard Constructor
* @param ctx context
* @param AD_AlertRecipient_ID id
* @param trxName transaction
*/
public MAlertRecipient (Properties ctx, int AD_AlertRecipient_ID, String trxName)
{
super (ctx, AD_AlertRecipient_ID, trxName);
} // MAlertRecipient
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlertRecipient (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAlertRecipient
/**
* Get User
* @return AD_User_ID or -1 if none
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value("AD_User_ID");
if (ii == null)
return -1;
return ii.intValue();
} // getAD_User_ID
/**
* Get Role
* @return AD_Role_ID or -1 if none
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value("AD_Role_ID");
if (ii == null)
return -1;
return ii.intValue();
} // getAD_Role_ID
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlertRecipient[");
sb.append(get_ID())
.append(",AD_User_ID=").append(getAD_User_ID())
.append(",AD_Role_ID=").append(getAD_Role_ID())
.append ("]");
return sb.toString ();
} // toString
} // MAlertRecipient

View File

@ -0,0 +1,99 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* Alert Rule Model
*
* @author Jorg Janke
* @version $Id: MAlertRule.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAlertRule extends X_AD_AlertRule
{
/**
* Standatd Constructor
* @param ctx context
* @param AD_AlertRule_ID id
* @param trxName transaction
*/
public MAlertRule (Properties ctx, int AD_AlertRule_ID, String trxName)
{
super (ctx, AD_AlertRule_ID, trxName);
} // MAlertRule
/**
* Standard Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlertRule (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAlertRule
/**
* Get Sql
* @return sql
*/
public String getSql()
{
StringBuffer sql = new StringBuffer();
sql.append("SELECT ").append(getSelectClause())
.append(" FROM ").append(getFromClause());
if (getWhereClause() != null && getWhereClause().length() > 0)
sql.append(" WHERE ").append(getWhereClause());
if (getOtherClause() != null && getOtherClause().length() > 0)
sql.append(" ").append(getOtherClause());
return sql.toString();
} // getSql
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (newRecord)
setIsValid(true);
if (isValid())
setErrorMsg(null);
return true;
} // beforeSave
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlertRule[");
sb.append(get_ID())
.append("-").append(getName())
.append(",Valid=").append(isValid())
.append(",").append(getSql());
sb.append ("]");
return sb.toString ();
} // toString
} // MAlertRule

View File

@ -0,0 +1,683 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.io.*;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.process.*;
import org.compiere.util.*;
/**
* Payment Allocation Model.
* Allocation Trigger update C_BPartner
*
* @author Jorg Janke
* @version $Id: MAllocationHdr.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public final class MAllocationHdr extends X_C_AllocationHdr implements DocAction
{
/**
* Get Allocations of Payment
* @param ctx context
* @param C_Payment_ID payment
* @return allocations of payment
* @param trxName transaction
*/
public static MAllocationHdr[] getOfPayment (Properties ctx, int C_Payment_ID, String trxName)
{
String sql = "SELECT * FROM C_AllocationHdr h "
+ "WHERE IsActive='Y'"
+ " AND EXISTS (SELECT * FROM C_AllocationLine l "
+ "WHERE h.C_AllocationHdr_ID=l.C_AllocationHdr_ID AND l.C_Payment_ID=?)";
ArrayList<MAllocationHdr> list = new ArrayList<MAllocationHdr>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, C_Payment_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add (new MAllocationHdr(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;
}
MAllocationHdr[] retValue = new MAllocationHdr[list.size()];
list.toArray(retValue);
return retValue;
} // getOfPayment
/**
* Get Allocations of Invoice
* @param ctx context
* @param C_Invoice_ID payment
* @return allocations of payment
* @param trxName transaction
*/
public static MAllocationHdr[] getOfInvoice (Properties ctx, int C_Invoice_ID, String trxName)
{
String sql = "SELECT * FROM C_AllocationHdr h "
+ "WHERE IsActive='Y'"
+ " AND EXISTS (SELECT * FROM C_AllocationLine l "
+ "WHERE h.C_AllocationHdr_ID=l.C_AllocationHdr_ID AND l.C_Invoice_ID=?)";
ArrayList<MAllocationHdr> list = new ArrayList<MAllocationHdr>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, C_Invoice_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add (new MAllocationHdr(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;
}
MAllocationHdr[] retValue = new MAllocationHdr[list.size()];
list.toArray(retValue);
return retValue;
} // getOfInvoice
/** Logger */
private static CLogger s_log = CLogger.getCLogger(MAllocationHdr.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param C_AllocationHdr_ID id
* @param trxName transaction
*/
public MAllocationHdr (Properties ctx, int C_AllocationHdr_ID, String trxName)
{
super (ctx, C_AllocationHdr_ID, trxName);
if (C_AllocationHdr_ID == 0)
{
// setDocumentNo (null);
setDateTrx (new Timestamp(System.currentTimeMillis()));
setDateAcct (getDateTrx());
setDocAction (DOCACTION_Complete); // CO
setDocStatus (DOCSTATUS_Drafted); // DR
// setC_Currency_ID (0);
setApprovalAmt (Env.ZERO);
setIsApproved (false);
setIsManual (false);
//
setPosted (false);
setProcessed (false);
setProcessing(false);
}
} // MAllocation
/**
* Mandatory New Constructor
* @param ctx context
* @param IsManual manual trx
* @param DateTrx date (if null today)
* @param C_Currency_ID currency
* @param description description
* @param trxName transaction
*/
public MAllocationHdr (Properties ctx, boolean IsManual, Timestamp DateTrx,
int C_Currency_ID, String description, String trxName)
{
this (ctx, 0, trxName);
setIsManual(IsManual);
if (DateTrx != null)
{
setDateTrx (DateTrx);
setDateAcct (DateTrx);
}
setC_Currency_ID (C_Currency_ID);
if (description != null)
setDescription(description);
} // create Allocation
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAllocationHdr (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAllocation
/** Lines */
private MAllocationLine[] m_lines = null;
/**
* Get Lines
* @param requery if true requery
* @return lines
*/
public MAllocationLine[] getLines (boolean requery)
{
if (m_lines != null && m_lines.length != 0 && !requery)
return m_lines;
//
String sql = "SELECT * FROM C_AllocationLine WHERE C_AllocationHdr_ID=?";
ArrayList<MAllocationLine> list = new ArrayList<MAllocationLine>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_AllocationHdr_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
MAllocationLine line = new MAllocationLine(getCtx(), rs, get_TrxName());
line.setParent(this);
list.add (line);
}
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;
}
//
m_lines = new MAllocationLine[list.size ()];
list.toArray (m_lines);
return m_lines;
} // getLines
/**
* Set Processed
* @param processed Processed
*/
public void setProcessed (boolean processed)
{
super.setProcessed (processed);
if (get_ID() == 0)
return;
String sql = "UPDATE C_AllocationHdr SET Processed='"
+ (processed ? "Y" : "N")
+ "' WHERE C_AllocationHdr_ID=" + getC_AllocationHdr_ID();
int no = DB.executeUpdate(sql, get_TrxName());
m_lines = null;
log.fine(processed + " - #" + no);
} // setProcessed
/**************************************************************************
* Before Save
* @param newRecord
* @return save
*/
protected boolean beforeSave (boolean newRecord)
{
// Changed from Not to Active
if (!newRecord && is_ValueChanged("IsActive") && isActive())
{
log.severe ("Cannot Re-Activate deactivated Allocations");
return false;
}
return true;
} // beforeSave
/**
* Before Delete.
* @return true if acct was deleted
*/
protected boolean beforeDelete ()
{
String trxName = get_TrxName();
if (trxName == null || trxName.length() == 0)
log.warning ("No transaction");
if (isPosted())
{
if (!MPeriod.isOpen(getCtx(), getDateTrx(), MDocType.DOCBASETYPE_PaymentAllocation))
{
log.warning ("Period Closed");
return false;
}
setPosted(false);
if (MFactAcct.delete (Table_ID, get_ID(), trxName) < 0)
return false;
}
// Mark as Inactive
setIsActive(false); // updated DB for line delete/process
String sql = "UPDATE C_AllocationHdr SET IsActive='N' WHERE C_AllocationHdr_ID=?";
DB.executeUpdate(sql, getC_AllocationHdr_ID(), trxName);
// Unlink
getLines(true);
HashSet<Integer> bps = new HashSet<Integer>();
for (int i = 0; i < m_lines.length; i++)
{
MAllocationLine line = m_lines[i];
bps.add(new Integer(line.getC_BPartner_ID()));
if (!line.delete(true, trxName))
return false;
}
updateBP(bps);
return true;
} // beforeDelete
/**
* After Save
* @param newRecord
* @param success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
return success;
} // afterSave
/**************************************************************************
* Process document
* @param processAction document action
* @return true if performed
*/
public boolean processIt (String processAction)
{
m_processMsg = null;
DocumentEngine engine = new DocumentEngine (this, getDocStatus());
return engine.processIt (processAction, getDocAction());
} // processIt
/** Process Message */
private String m_processMsg = null;
/** Just Prepared Flag */
private boolean m_justPrepared = false;
/**
* Unlock Document.
* @return true if success
*/
public boolean unlockIt()
{
log.info(toString());
setProcessing(false);
return true;
} // unlockIt
/**
* Invalidate Document
* @return true if success
*/
public boolean invalidateIt()
{
log.info(toString());
setDocAction(DOCACTION_Prepare);
return true;
} // invalidateIt
/**
* Prepare Document
* @return new status (In Progress or Invalid)
*/
public String prepareIt()
{
log.info(toString());
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE);
if (m_processMsg != null)
return DocAction.STATUS_Invalid;
// Std Period open?
if (!MPeriod.isOpen(getCtx(), getDateAcct(), MDocType.DOCBASETYPE_PaymentAllocation))
{
m_processMsg = "@PeriodClosed@";
return DocAction.STATUS_Invalid;
}
getLines(false);
if (m_lines.length == 0)
{
m_processMsg = "@NoLines@";
return DocAction.STATUS_Invalid;
}
// Add up Amounts & validate
BigDecimal approval = Env.ZERO;
for (int i = 0; i < m_lines.length; i++)
{
MAllocationLine line = m_lines[i];
approval = approval.add(line.getWriteOffAmt()).add(line.getDiscountAmt());
// Make sure there is BP
if (line.getC_BPartner_ID() == 0)
{
m_processMsg = "No Business Partner";
return DocAction.STATUS_Invalid;
}
}
setApprovalAmt(approval);
//
m_justPrepared = true;
if (!DOCACTION_Complete.equals(getDocAction()))
setDocAction(DOCACTION_Complete);
return DocAction.STATUS_InProgress;
} // prepareIt
/**
* Approve Document
* @return true if success
*/
public boolean approveIt()
{
log.info(toString());
setIsApproved(true);
return true;
} // approveIt
/**
* Reject Approval
* @return true if success
*/
public boolean rejectIt()
{
log.info(toString());
setIsApproved(false);
return true;
} // rejectIt
/**
* Complete Document
* @return new status (Complete, In Progress, Invalid, Waiting ..)
*/
public String completeIt()
{
// Re-Check
if (!m_justPrepared)
{
String status = prepareIt();
if (!DocAction.STATUS_InProgress.equals(status))
return status;
}
// Implicit Approval
if (!isApproved())
approveIt();
log.info(toString());
// Link
getLines(false);
HashSet<Integer> bps = new HashSet<Integer>();
for (int i = 0; i < m_lines.length; i++)
{
MAllocationLine line = m_lines[i];
bps.add(new Integer(line.processIt(false))); // not reverse
}
updateBP(bps);
// User Validation
String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE);
if (valid != null)
{
m_processMsg = valid;
return DocAction.STATUS_Invalid;
}
setProcessed(true);
setDocAction(DOCACTION_Close);
return DocAction.STATUS_Completed;
} // completeIt
/**
* Void Document.
* Same as Close.
* @return true if success
*/
public boolean voidIt()
{
log.info(toString());
boolean retValue = reverseIt();
setDocAction(DOCACTION_None);
return retValue;
} // voidIt
/**
* Close Document.
* Cancel not delivered Qunatities
* @return true if success
*/
public boolean closeIt()
{
log.info(toString());
setDocAction(DOCACTION_None);
return true;
} // closeIt
/**
* Reverse Correction
* @return true if success
*/
public boolean reverseCorrectIt()
{
log.info(toString());
boolean retValue = reverseIt();
setDocAction(DOCACTION_None);
return retValue;
} // reverseCorrectionIt
/**
* Reverse Accrual - none
* @return false
*/
public boolean reverseAccrualIt()
{
log.info(toString());
boolean retValue = reverseIt();
setDocAction(DOCACTION_None);
return retValue;
} // reverseAccrualIt
/**
* Re-activate
* @return false
*/
public boolean reActivateIt()
{
log.info(toString());
return false;
} // reActivateIt
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAllocationHdr[");
sb.append(get_ID()).append("-").append(getSummary()).append ("]");
return sb.toString ();
} // toString
/**
* Get Document Info
* @return document info (untranslated)
*/
public String getDocumentInfo()
{
return Msg.getElement(getCtx(), "C_AllocationHdr_ID") + " " + getDocumentNo();
} // getDocumentInfo
/**
* Create PDF
* @return File or null
*/
public File createPDF ()
{
try
{
File temp = File.createTempFile(get_TableName()+get_ID()+"_", ".pdf");
return createPDF (temp);
}
catch (Exception e)
{
log.severe("Could not create PDF - " + e.getMessage());
}
return null;
} // getPDF
/**
* Create PDF file
* @param file output file
* @return file if success
*/
public File createPDF (File file)
{
// ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID());
// if (re == null)
return null;
// return re.getPDF(file);
} // createPDF
/*************************************************************************
* Get Summary
* @return Summary of Document
*/
public String getSummary()
{
StringBuffer sb = new StringBuffer();
sb.append(getDocumentNo());
// : Total Lines = 123.00 (#1)
sb.append(": ")
.append(Msg.translate(getCtx(),"ApprovalAmt")).append("=").append(getApprovalAmt())
.append(" (#").append(getLines(false).length).append(")");
// - Description
if (getDescription() != null && getDescription().length() > 0)
sb.append(" - ").append(getDescription());
return sb.toString();
} // getSummary
/**
* Get Process Message
* @return clear text error message
*/
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
* @return AD_User_ID
*/
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**************************************************************************
* Reverse Allocation.
* Period needs to be open
* @return true if reversed
*/
private boolean reverseIt()
{
if (!isActive())
throw new IllegalStateException("Allocation already reversed (not active)");
// Can we delete posting
if (!MPeriod.isOpen(getCtx(), getDateTrx(), MPeriodControl.DOCBASETYPE_PaymentAllocation))
throw new IllegalStateException("@PeriodClosed@");
// Set Inactive
setIsActive (false);
setDocumentNo(getDocumentNo()+"^");
setDocStatus(DOCSTATUS_Reversed); // for direct calls
if (!save() || isActive())
throw new IllegalStateException("Cannot de-activate allocation");
// Delete Posting
String sql = "DELETE FROM Fact_Acct WHERE AD_Table_ID=" + MAllocationHdr.Table_ID
+ " AND Record_ID=" + getC_AllocationHdr_ID();
int no = DB.executeUpdate(sql, get_TrxName());
log.fine("Fact_Acct deleted #" + no);
// Unlink Invoices
getLines(true);
HashSet<Integer> bps = new HashSet<Integer>();
for (int i = 0; i < m_lines.length; i++)
{
MAllocationLine line = m_lines[i];
line.setIsActive(false);
line.save();
bps.add(new Integer(line.processIt(true))); // reverse
}
updateBP(bps);
return true;
} // reverse
/**
* Update Open Balance of BP's
* @param bps list of business partners
*/
private void updateBP(HashSet<Integer> bps)
{
log.info("#" + bps.size());
Iterator<Integer> it = bps.iterator();
while (it.hasNext())
{
int C_BPartner_ID = it.next();
MBPartner bp = new MBPartner(getCtx(), C_BPartner_ID, get_TrxName());
bp.setTotalOpenBalance(); // recalculates from scratch
// bp.setSOCreditStatus(); // called automatically
if (bp.save())
log.fine(bp.toString());
else
log.log(Level.SEVERE, "BP not updated - " + bp);
}
} // updateBP
} // MAllocation

View File

@ -0,0 +1,337 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Allocation Line Model
*
* @author Jorg Janke
* @version $Id: MAllocationLine.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAllocationLine extends X_C_AllocationLine
{
/**
* Standard Constructor
* @param ctx context
* @param C_AllocationLine_ID id
* @param trxName name
*/
public MAllocationLine (Properties ctx, int C_AllocationLine_ID, String trxName)
{
super (ctx, C_AllocationLine_ID, trxName);
if (C_AllocationLine_ID == 0)
{
// setC_AllocationHdr_ID (0);
setAmount (Env.ZERO);
setDiscountAmt (Env.ZERO);
setWriteOffAmt (Env.ZERO);
setOverUnderAmt(Env.ZERO);
}
} // MAllocationLine
/**
* Load Constructor
* @param ctx ctx
* @param rs result set
* @param trxName transaction
*/
public MAllocationLine (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAllocationLine
/**
* Parent Constructor
* @param parent parent
*/
public MAllocationLine (MAllocationHdr parent)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setC_AllocationHdr_ID(parent.getC_AllocationHdr_ID());
m_parent = parent;
set_TrxName(parent.get_TrxName());
} // MAllocationLine
/**
* Parent Constructor
* @param parent parent
* @param Amount amount
* @param DiscountAmt optional discount
* @param WriteOffAmt optional write off
* @param OverUnderAmt over/underpayment
*/
public MAllocationLine (MAllocationHdr parent, BigDecimal Amount,
BigDecimal DiscountAmt, BigDecimal WriteOffAmt, BigDecimal OverUnderAmt)
{
this (parent);
setAmount (Amount);
setDiscountAmt (DiscountAmt == null ? Env.ZERO : DiscountAmt);
setWriteOffAmt (WriteOffAmt == null ? Env.ZERO : WriteOffAmt);
setOverUnderAmt (OverUnderAmt == null ? Env.ZERO : OverUnderAmt);
} // MAllocationLine
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MAllocationLine.class);
/** Invoice info */
private MInvoice m_invoice = null;
/** Allocation Header */
private MAllocationHdr m_parent = null;
/**
* Get Parent
* @return parent
*/
public MAllocationHdr getParent()
{
if (m_parent == null)
m_parent = new MAllocationHdr (getCtx(), getC_AllocationHdr_ID(), get_TrxName());
return m_parent;
} // getParent
/**
* Set Parent
* @param parent parent
*/
protected void setParent (MAllocationHdr parent)
{
m_parent = parent;
} // setParent
/**
* Get Parent Trx Date
* @return date trx
*/
public Timestamp getDateTrx ()
{
return getParent().getDateTrx ();
} // getDateTrx
/**
* Set Document Info
* @param C_BPartner_ID partner
* @param C_Order_ID order
* @param C_Invoice_ID invoice
*/
public void setDocInfo (int C_BPartner_ID, int C_Order_ID, int C_Invoice_ID)
{
setC_BPartner_ID(C_BPartner_ID);
setC_Order_ID(C_Order_ID);
setC_Invoice_ID(C_Invoice_ID);
} // setDocInfo
/**
* Set Payment Info
* @param C_Payment_ID payment
* @param C_CashLine_ID cash line
*/
public void setPaymentInfo (int C_Payment_ID, int C_CashLine_ID)
{
if (C_Payment_ID != 0)
setC_Payment_ID(C_Payment_ID);
if (C_CashLine_ID != 0)
setC_CashLine_ID(C_CashLine_ID);
} // setPaymentInfo
/**
* Get Invoice
* @return invoice or null
*/
public MInvoice getInvoice()
{
if (m_invoice == null && getC_Invoice_ID() != 0)
m_invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName());
return m_invoice;
} // getInvoice
/**************************************************************************
* Before Save
* @param newRecord
* @return save
*/
protected boolean beforeSave (boolean newRecord)
{
if (!newRecord
&& (is_ValueChanged("C_BPartner_ID") || is_ValueChanged("C_Invoice_ID")))
{
log.severe ("Cannot Change Business Partner or Invoice");
return false;
}
// Set BPartner/Order from Invoice
if (getC_BPartner_ID() == 0 && getInvoice() != null)
setC_BPartner_ID(getInvoice().getC_BPartner_ID());
if (getC_Order_ID() == 0 && getInvoice() != null)
setC_Order_ID(getInvoice().getC_Order_ID());
//
return true;
} // beforeSave
/**
* Before Delete
* @return true if reversed
*/
protected boolean beforeDelete ()
{
setIsActive(false);
processIt(true);
return true;
} // beforeDelete
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAllocationLine[");
sb.append(get_ID());
if (getC_Payment_ID() != 0)
sb.append(",C_Payment_ID=").append(getC_Payment_ID());
if (getC_CashLine_ID() != 0)
sb.append(",C_CashLine_ID=").append(getC_CashLine_ID());
if (getC_Invoice_ID() != 0)
sb.append(",C_Invoice_ID=").append(getC_Invoice_ID());
if (getC_BPartner_ID() != 0)
sb.append(",C_BPartner_ID=").append(getC_BPartner_ID());
sb.append(", Amount=").append(getAmount())
.append(",Discount=").append(getDiscountAmt())
.append(",WriteOff=").append(getWriteOffAmt())
.append(",OverUnder=").append(getOverUnderAmt());
sb.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
* Process Allocation (does not update line).
* - Update and Link Invoice/Payment/Cash
* @param reverse if true allocation is reversed
* @return C_BPartner_ID
*/
protected int processIt (boolean reverse)
{
log.fine("Reverse=" + reverse + " - " + toString());
int C_Invoice_ID = getC_Invoice_ID();
MInvoice invoice = getInvoice();
if (invoice != null
&& getC_BPartner_ID() != invoice.getC_BPartner_ID())
setC_BPartner_ID(invoice.getC_BPartner_ID());
//
int C_Payment_ID = getC_Payment_ID();
int C_CashLine_ID = getC_CashLine_ID();
// Update Payment
if (C_Payment_ID != 0)
{
MPayment payment = new MPayment (getCtx(), C_Payment_ID, get_TrxName());
if (getC_BPartner_ID() != payment.getC_BPartner_ID())
log.warning("C_BPartner_ID different - Invoice=" + getC_BPartner_ID() + " - Payment=" + payment.getC_BPartner_ID());
if (reverse)
{
if (!payment.isCashTrx())
{
payment.setIsAllocated(false);
payment.save();
}
}
else
{
if (payment.testAllocation())
payment.save();
}
}
// Payment - Invoice
if (C_Payment_ID != 0 && invoice != null)
{
// Link to Invoice
if (reverse)
{
invoice.setC_Payment_ID(0);
log.fine("C_Payment_ID=" + C_Payment_ID
+ " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
}
else if (invoice.isPaid())
{
invoice.setC_Payment_ID(C_Payment_ID);
log.fine("C_Payment_ID=" + C_Payment_ID
+ " Linked to C_Invoice_ID=" + C_Invoice_ID);
}
// Link to Order
String update = "UPDATE C_Order o "
+ "SET C_Payment_ID="
+ (reverse ? "NULL " : "(SELECT C_Payment_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
+ "WHERE EXISTS (SELECT * FROM C_Invoice i "
+ "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
if (DB.executeUpdate(update, get_TrxName()) > 0)
log.fine("C_Payment_ID=" + C_Payment_ID
+ (reverse ? " UnLinked from" : " Linked to")
+ " order of C_Invoice_ID=" + C_Invoice_ID);
}
// Cash - Invoice
if (C_CashLine_ID != 0 && invoice != null)
{
// Link to Invoice
if (reverse)
{
invoice.setC_CashLine_ID(0);
log.fine("C_CashLine_ID=" + C_CashLine_ID
+ " Unlinked from C_Invoice_ID=" + C_Invoice_ID);
}
else
{
invoice.setC_CashLine_ID(C_CashLine_ID);
log.fine("C_CashLine_ID=" + C_CashLine_ID
+ " Linked to C_Invoice_ID=" + C_Invoice_ID);
}
// Link to Order
String update = "UPDATE C_Order o "
+ "SET C_CashLine_ID="
+ (reverse ? "NULL " : "(SELECT C_CashLine_ID FROM C_Invoice WHERE C_Invoice_ID=" + C_Invoice_ID + ") ")
+ "WHERE EXISTS (SELECT * FROM C_Invoice i "
+ "WHERE o.C_Order_ID=i.C_Order_ID AND i.C_Invoice_ID=" + C_Invoice_ID + ")";
if (DB.executeUpdate(update, get_TrxName()) > 0)
log.fine("C_CashLine_ID=" + C_CashLine_ID
+ (reverse ? " UnLinked from" : " Linked to")
+ " order of C_Invoice_ID=" + C_Invoice_ID);
}
// Update Balance / Credit used - Counterpart of MInvoice.completeIt
if (invoice != null)
{
if (invoice.testAllocation()
&& !invoice.save())
log.log(Level.SEVERE, "Invoice not updated - " + invoice);
}
return getC_BPartner_ID();
} // processIt
} // MAllocationLine

View File

@ -0,0 +1,456 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.servlet.http.*;
import org.compiere.util.*;
/**
* Asset Model
*
* @author Jorg Janke
* @version $Id: MAsset.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAsset extends X_A_Asset
{
/**
* Get Asset From Shipment
* @param ctx context
* @param M_InOutLine_ID shipment line
* @param trxName transaction
* @return asset or null
*/
public static MAsset getFromShipment (Properties ctx, int M_InOutLine_ID, String trxName)
{
MAsset retValue = null;
String sql = "SELECT * FROM A_Asset WHERE M_InOutLine_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, trxName);
pstmt.setInt (1, M_InOutLine_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
retValue = new MAsset (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 retValue;
} // getFromShipment
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MAsset.class);
/**************************************************************************
* Asset Constructor
* @param ctx context
* @param A_Asset_ID asset
* @param trxName transaction name
*/
public MAsset (Properties ctx, int A_Asset_ID, String trxName)
{
super (ctx, A_Asset_ID, trxName);
if (A_Asset_ID == 0)
{
setIsDepreciated (false);
setIsFullyDepreciated (false);
// setValue (null);
// setName (null);
setIsInPosession (false);
setIsOwned (false);
// setA_Asset_Group_ID (0);
setIsDisposed (false);
setM_AttributeSetInstance_ID(0);
setQty(Env.ONE);
}
} // MAsset
/**
* Discontinued Asset Constructor - DO NOT USE (but don't delete either)
* @param ctx context
* @param A_Asset_ID asset
*/
public MAsset (Properties ctx, int A_Asset_ID)
{
this (ctx, A_Asset_ID, null);
} // MAsset
/**
* Load Constructor
* @param ctx context
* @param rs result set record
* @param trxName transaction
*/
public MAsset (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAsset
/**
* Shipment Constructor
* @param shipment shipment
* @param shipLine shipment line
* @param deliveryCount 0 or number of delivery
*/
public MAsset (MInOut shipment, MInOutLine shipLine, int deliveryCount)
{
this (shipment.getCtx(), 0, shipment.get_TrxName());
setClientOrg(shipment);
setValueNameDescription(shipment, shipLine, deliveryCount);
// Header
setAssetServiceDate(shipment.getMovementDate());
setIsOwned(false);
setC_BPartner_ID(shipment.getC_BPartner_ID());
setC_BPartner_Location_ID(shipment.getC_BPartner_Location_ID());
setAD_User_ID(shipment.getAD_User_ID());
// Line
MProduct product = shipLine.getProduct();
setM_Product_ID(product.getM_Product_ID());
setA_Asset_Group_ID(product.getA_Asset_Group_ID());
// Guarantee & Version
setGuaranteeDate(TimeUtil.addDays(shipment.getMovementDate(), product.getGuaranteeDays()));
setVersionNo(product.getVersionNo());
if (shipLine.getM_AttributeSetInstance_ID() != 0)
{
MAttributeSetInstance asi = new MAttributeSetInstance (getCtx(), shipLine.getM_AttributeSetInstance_ID(), get_TrxName());
setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID());
setLot(asi.getLot());
setSerNo(asi.getSerNo());
}
setHelp(shipLine.getDescription());
if (deliveryCount != 0)
setQty(shipLine.getMovementQty());
setM_InOutLine_ID(shipLine.getM_InOutLine_ID());
// Activate
MAssetGroup ag = MAssetGroup.get(getCtx(), getA_Asset_Group_ID());
if (!ag.isCreateAsActive())
setIsActive(false);
} // MAsset
/** Product Info */
private MProduct m_product = null;
/**
* Set Value Name Description
* @param shipment shipment
* @param line line
* @param deliveryCount
*/
public void setValueNameDescription(MInOut shipment, MInOutLine line,
int deliveryCount)
{
MProduct product = line.getProduct();
MBPartner partner = shipment.getBPartner();
setValueNameDescription(shipment, deliveryCount, product, partner);
} // setValueNameDescription
/**
* Set Value, Name, Description
* @param shipment shipment
* @param deliveryCount count
* @param product product
* @param partner partner
*/
public void setValueNameDescription (MInOut shipment,
int deliveryCount, MProduct product, MBPartner partner)
{
String documentNo = "_" + shipment.getDocumentNo();
if (deliveryCount > 1)
documentNo += "_" + deliveryCount;
// Value
String value = partner.getValue() + "_" + product.getValue();
if (value.length() > 40-documentNo.length())
value = value.substring(0,40-documentNo.length()) + documentNo;
setValue(value);
// Name MProduct.afterSave
String name = partner.getName() + " - " + product.getName();
if (name.length() > 60)
name = name.substring(0,60);
setName(name);
// Description
String description = product.getDescription();
setDescription(description);
} // setValueNameDescription
/**
* Add to Description
* @param description text
*/
public void addDescription (String description)
{
String desc = getDescription();
if (desc == null)
setDescription(description);
else
setDescription(desc + " | " + description);
} // addDescription
/**
* Get Qty
* @return 1 or Qty
*/
public BigDecimal getQty ()
{
BigDecimal qty = super.getQty();
if (qty == null || qty.equals(Env.ZERO))
setQty(Env.ONE);
return super.getQty();
} // getQty
/**
* String representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAsset[")
.append (get_ID ())
.append("-").append(getValue())
.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
* Get Deliveries
* @return deliveries
*/
public MAssetDelivery[] getDeliveries()
{
ArrayList<MAssetDelivery> list = new ArrayList<MAssetDelivery>();
String sql = "SELECT * FROM A_Asset_Delivery WHERE A_Asset_ID=? ORDER BY Created DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, getA_Asset_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add(new MAssetDelivery(getCtx(), rs, get_TrxName()));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, sql, e);
}
finally
{
try
{
if (pstmt != null)
pstmt.close ();
}
catch (Exception e)
{}
pstmt = null;
}
//
MAssetDelivery[] retValue = new MAssetDelivery[list.size()];
list.toArray(retValue);
return retValue;
} // getDeliveries
/**
* Get Delivery count
* @return delivery count
*/
public int getDeliveryCount()
{
String sql = "SELECT COUNT(*) FROM A_Asset_Delivery WHERE A_Asset_ID=?";
return DB.getSQLValue(get_TrxName(),
sql, getA_Asset_ID());
} // getDeliveries
/**************************************************************************
* Can we download.
* Based on guarantee date and availability of download
* @return true if downloadable
*/
public boolean isDownloadable()
{
if (!isActive())
return false;
// Guarantee Date
Timestamp guarantee = getGuaranteeDate();
if (guarantee == null)
return false;
guarantee = TimeUtil.getDay(guarantee);
Timestamp now = TimeUtil.getDay(System.currentTimeMillis());
// valid
if (!now.after(guarantee)) // not after guarantee date
{
getProduct();
return m_product != null
&& m_product.hasDownloads();
}
//
return false;
} // isDownloadable
/**************************************************************************
* Get Product Version No
* @return VersionNo
*/
public String getProductVersionNo()
{
return getProduct().getVersionNo();
} // getProductVersionNo
/**
* Get Product R_MailText_ID
* @return R_MailText_ID
*/
public int getProductR_MailText_ID()
{
return getProduct().getR_MailText_ID();
} // getProductR_MailText_ID
/**
* Get Product Info
* @return product
*/
private MProduct getProduct()
{
if (m_product == null)
m_product = MProduct.get (getCtx(), getM_Product_ID());
return m_product;
} // getProductInfo
/**
* Get Active Addl. Product Downloads
* @return array of downloads
*/
public MProductDownload[] getProductDownloads()
{
if (m_product == null)
getProduct();
if (m_product != null)
return m_product.getProductDownloads(false);
return null;
} // getProductDownloads
/**
* Get Additional Download Names
* @return names
*/
public String[] getDownloadNames()
{
MProductDownload[] dls = getProductDownloads();
if (dls != null && dls.length > 0)
{
String[] retValue = new String[dls.length];
for (int i = 0; i < retValue.length; i++)
retValue[i] = dls[i].getName();
log.fine("#" + dls.length);
return retValue;
}
return new String[]{};
} // addlDownloadNames
/**
* Get Additional Download URLs
* @return URLs
*/
public String[] getDownloadURLs()
{
MProductDownload[] dls = getProductDownloads();
if (dls != null && dls.length > 0)
{
String[] retValue = new String[dls.length];
for (int i = 0; i < retValue.length; i++)
{
String url = dls[i].getDownloadURL();
int pos = Math.max(url.lastIndexOf('/'), url.lastIndexOf('\\'));
if (pos != -1)
url = url.substring(pos+1);
retValue[i] = url;
}
return retValue;
}
return new String[]{};
} // addlDownloadURLs
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
getQty(); // set to 1
return true;
} // beforeSave
/*************************************************************************
* Confirm Asset EMail Delivery
* @param email email sent
* @param AD_User_ID recipient
* @return asset delivery
*/
public MAssetDelivery confirmDelivery (EMail email, int AD_User_ID)
{
setVersionNo(getProductVersionNo());
MAssetDelivery ad = new MAssetDelivery (this, email, AD_User_ID);
return ad;
} // confirmDelivery
/**
* Confirm Asset Download Delivery
* @param request request
* @param AD_User_ID recipient
* @return asset delivery
*/
public MAssetDelivery confirmDelivery (HttpServletRequest request, int AD_User_ID)
{
setVersionNo(getProductVersionNo());
setLifeUseUnits(getLifeUseUnits()+1);
MAssetDelivery ad = new MAssetDelivery (this, request, AD_User_ID);
return ad;
} // confirmDelivery
} // MAsset

View File

@ -0,0 +1,128 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import javax.servlet.http.*;
import org.compiere.util.*;
/**
* Asset Delivery Model
*
* @author Jorg Janke
* @version $Id: MAssetDelivery.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAssetDelivery extends X_A_Asset_Delivery
{
/**
* Constructor
* @param ctx context
* @param A_Asset_Delivery_ID id or 0
* @param trxName trx
*/
public MAssetDelivery (Properties ctx, int A_Asset_Delivery_ID, String trxName)
{
super (ctx, A_Asset_Delivery_ID, trxName);
if (A_Asset_Delivery_ID == 0)
{
setMovementDate (new Timestamp (System.currentTimeMillis ()));
}
} // MAssetDelivery
/**
* Load Constructor
* @param ctx context
* @param rs result set record
* @param trxName transaction
*/
public MAssetDelivery (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAssetDelivery
/**
* Create Asset Delivery for HTTP Request
* @param asset asset
* @param request request
* @param AD_User_ID BP Contact
*/
public MAssetDelivery (MAsset asset,
HttpServletRequest request, int AD_User_ID)
{
super (asset.getCtx(), 0, asset.get_TrxName());
setAD_Client_ID(asset.getAD_Client_ID());
setAD_Org_ID(asset.getAD_Org_ID());
// Asset Info
setA_Asset_ID (asset.getA_Asset_ID());
setLot(asset.getLot());
setSerNo(asset.getSerNo());
setVersionNo(asset.getVersionNo());
//
setMovementDate (new Timestamp (System.currentTimeMillis ()));
// Request
setURL(request.getRequestURL().toString());
setReferrer(request.getHeader("Referer"));
setRemote_Addr(request.getRemoteAddr());
setRemote_Host(request.getRemoteHost());
// Who
setAD_User_ID(AD_User_ID);
//
save();
} // MAssetDelivery
/**
* Create Asset Delivery for EMail
* @param asset asset
* @param email email
* @param AD_User_ID BP Contact
*/
public MAssetDelivery (MAsset asset, EMail email, int AD_User_ID)
{
super (asset.getCtx(), 0, asset.get_TrxName());
// Asset Info
setA_Asset_ID (asset.getA_Asset_ID());
setLot(asset.getLot());
setSerNo(asset.getSerNo());
setVersionNo(asset.getVersionNo());
//
setMovementDate (new Timestamp (System.currentTimeMillis ()));
// EMail
setEMail(email.getTo().toString());
setMessageID(email.getMessageID());
// Who
setAD_User_ID(AD_User_ID);
//
save();
} // MAssetDelivery
/**
* String representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAssetDelivery[")
.append (get_ID ())
.append(",A_Asset_ID=").append(getA_Asset_ID())
.append(",MovementDate=").append(getMovementDate())
.append ("]");
return sb.toString ();
} // toString
} // MAssetDelivery

View File

@ -0,0 +1,80 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Asset Group Model
*
* @author Jorg Janke
* @version $Id: MAssetGroup.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class MAssetGroup extends X_A_Asset_Group
{
/**
* Get from Cache
* @param ctx context
* @param A_Asset_Group_ID id
* @return category
*/
public static MAssetGroup get (Properties ctx, int A_Asset_Group_ID)
{
Integer ii = new Integer (A_Asset_Group_ID);
MAssetGroup pc = (MAssetGroup)s_cache.get(ii);
if (pc == null)
pc = new MAssetGroup (ctx, A_Asset_Group_ID, null);
return pc;
} // get
/** Categopry Cache */
private static CCache s_cache = new CCache ("A_Asset_Group", 10);
/**
* Standard Constructor
* @param ctx context
* @param A_Asset_Group_ID id
* @param trxName trx
*/
public MAssetGroup (Properties ctx, int A_Asset_Group_ID, String trxName)
{
super (ctx, A_Asset_Group_ID, trxName);
if (A_Asset_Group_ID == 0)
{
// setName (null);
setIsDepreciated (false);
setIsOneAssetPerUOM (false);
setIsOwned (false);
setIsCreateAsActive(true);
setIsTrackIssues(false);
}
} // MAssetGroup
/**
* Load Cosntructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MAssetGroup (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MAssetGroup
} // MAssetGroup

View File

@ -0,0 +1,665 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.awt.*;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Assignment Slot.
* Display Information about Assignment Slot
*
* @author Jorg Janke
* @version $Id: MAssignmentSlot.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAssignmentSlot implements Comparator
{
/**
* Comparator Constructor
*/
public MAssignmentSlot ()
{
this (null, null, null, null, STATUS_TimeSlot);
} // MAssignmentSlot
/**
* Timeslot Constructor
* @param startTime start time
* @param endTime end time
*/
public MAssignmentSlot (Timestamp startTime, Timestamp endTime)
{
this (startTime, endTime, null, null, STATUS_TimeSlot);
setDisplay(DISPLAY_TIME_FROM);
} // MAssignmentSlot
/**
* Timeslot Constructor
* @param startTime start time
* @param endTime end time
*/
public MAssignmentSlot (long startTime, long endTime)
{
this (new Timestamp(startTime), new Timestamp(endTime), null, null, STATUS_TimeSlot);
setDisplay(DISPLAY_TIME_FROM);
} // MAssignmentSlot
/**
* Non Assignment Constructor
* @param startTime start time
* @param endTime end time
* @param name name
* @param description description
* @param status status
*/
public MAssignmentSlot (Timestamp startTime, Timestamp endTime,
String name, String description, int status)
{
setStartTime(startTime);
setEndTime(endTime);
setName(name);
setDescription(description);
setStatus(status);
//
// log.fine( toString());
} // MAssignmentSlot
/**
* Assignment Constructor
* @param assignment MAssignment
*/
public MAssignmentSlot (MResourceAssignment assignment)
{
setStatus(assignment.isConfirmed() ? STATUS_Confirmed : STATUS_NotConfirmed);
setMAssignment(assignment);
// log.fine( toString());
} // MAssignmentSlot
/** Not Available Code */
public static final int STATUS_NotAvailable = 0;
/** Not Available Code */
public static final int STATUS_UnAvailable = 11;
/** Not Available Code */
public static final int STATUS_NonBusinessDay = 12;
/** Not Available Code */
public static final int STATUS_NotInSlotDay = 21;
/** Not Available Code */
public static final int STATUS_NotInSlotTime = 22;
/** Assignment Code */
public static final int STATUS_NotConfirmed = 101;
/** Assignment Code */
public static final int STATUS_Confirmed = 102;
/** Assignment Code */
public static final int STATUS_TimeSlot = 100000;
/** Start Time */
private Timestamp m_startTime;
/** End Time */
private Timestamp m_endTime;
/** Name */
private String m_name;
/** Description */
private String m_description;
/** Status */
private int m_status = STATUS_NotAvailable;
/** Y position */
private int m_yStart = 0;
private int m_yEnd = 0;
private int m_xPos = 0;
private int m_xMax = 1;
/** The assignment */
private MResourceAssignment m_mAssignment;
/** Language used for formatting */
private Language m_language = Language.getLoginLanguage();
/** toString displays everything */
public static final int DISPLAY_ALL = 0;
/** toString displays formatted time from */
public static final int DISPLAY_TIME_FROM = 1;
/** toString displays formatted time from-to */
public static final int DISPLAY_TIME_FROM_TO = 1;
/** toString displays formatted day time from-to */
public static final int DISPLAY_DATETIME_FROM_TO = 1;
/** toString displays name */
public static final int DISPLAY_NAME = 1;
/** toString displays name and optional description */
public static final int DISPLAY_NAME_DESCRIPTION = 1;
/** toString displays formatted all info */
public static final int DISPLAY_FULL = 1;
/** DisplayMode */
private int m_displayMode = DISPLAY_FULL;
/*************************************************************************/
/**
* Set Status
* @param status STATUS_..
*/
public void setStatus (int status)
{
m_status = status;
} // setStatus
/**
* Get Status
* @return STATUS_..
*/
public int getStatus()
{
return m_status;
} // getStatus
/**
* Is the Slot an Assignment?
* @return true if slot is an assignment
*/
public boolean isAssignment()
{
return (m_status == STATUS_NotConfirmed || m_status == STATUS_Confirmed);
} // isAssignment
/**
* Get Color for Status
* @param background true if background - or foreground
* @return Color
*/
public Color getColor (boolean background)
{
// Not found, Inactive, not available
if (m_status == STATUS_NotAvailable)
return background ? Color.gray : Color.magenta;
// Holiday
else if (m_status == STATUS_UnAvailable)
return background ? Color.gray : Color.pink;
// Vacation
else if (m_status == STATUS_NonBusinessDay)
return background ? Color.lightGray : Color.red;
// Out of normal hours
else if (m_status == STATUS_NotInSlotDay || m_status == STATUS_NotInSlotTime)
return background ? Color.lightGray : Color.black;
// Assigned
else if (m_status == STATUS_NotConfirmed)
return background ? Color.blue : Color.white;
// Confirmed
else if (m_status == STATUS_Confirmed)
return background ? Color.blue : Color.black;
// Unknown
return background ? Color.black : Color.white;
} // getColor
/*************************************************************************/
/**
* Get Start time
* @return start time
*/
public Timestamp getStartTime()
{
return m_startTime;
}
/**
* Set Start time
* @param startTime start time, if null use current time
*/
public void setStartTime (Timestamp startTime)
{
if (startTime == null)
m_startTime = new Timestamp(System.currentTimeMillis());
else
m_startTime = startTime;
} // setStartTime
/**
* Get End time
* @return end time
*/
public Timestamp getEndTime()
{
return m_endTime;
}
/**
* Set End time
* @param endTime end time, if null use start time
*/
public void setEndTime (Timestamp endTime)
{
if (endTime == null)
m_endTime = m_startTime;
else
m_endTime = endTime;
}
/*************************************************************************/
/**
* Set Assignment
* @param assignment MAssignment
*/
public void setMAssignment (MResourceAssignment assignment)
{
if (assignment == null)
return;
if (!isAssignment())
throw new IllegalArgumentException("Assignment Slot not an Assignment");
//
m_mAssignment = assignment;
setStartTime(m_mAssignment.getAssignDateFrom());
setEndTime(m_mAssignment.getAssignDateTo());
setName(m_mAssignment.getName());
setDescription(m_mAssignment.getDescription());
setStatus(m_mAssignment.isConfirmed() ? STATUS_Confirmed : STATUS_NotConfirmed);
} // setMAssignment
/**
* Get Assugnment
* @return assignment
*/
public MResourceAssignment getMAssignment()
{
return m_mAssignment;
} // getAssignment
/**
* Set Name
* @param name name
*/
public void setName (String name)
{
if (name == null)
m_name = "";
else
m_name = name;
} // setName
/**
* Get Name
* @return name
*/
public String getName()
{
return m_name;
} // getName
/**
* Set Description
* @param description description
*/
public void setDescription (String description)
{
if (description == null)
m_description = "";
else
m_description = description;
} // setDescription
/**
* Get Description
* @return description
*/
public String getDescription()
{
return m_description;
} // getDescription
/*************************************************************************/
/**
* Set Y position
* @param yStart zero based Y start index
* @param yEnd zero based Y end index
*/
public void setY (int yStart, int yEnd)
{
m_yStart = yStart;
m_yEnd = yEnd;
} // setY
/**
* Get Y start position
* @return zero based Y start index
*/
public int getYStart ()
{
return m_yStart;
} // getYStart
/**
* Get Y end position
* @return zero based Y end index
*/
public int getYEnd ()
{
return m_yEnd;
} // setYEnd
/**
* Set X position
* @param xPos zero based X position index
* @param xMax number of parallel columns
*/
public void setX (int xPos, int xMax)
{
m_xPos = xPos;
if (xMax > m_xMax)
m_xMax = xMax;
} // setX
/**
* Get X position
* @return zero based X position index
*/
public int getXPos()
{
return m_xPos;
} // setXPos
/**
* Get X columns
* @return number of parallel columns
*/
public int getXMax()
{
return m_xMax;
} // setXMax
/*************************************************************************/
/**
* Set Language
* @param language language
*/
public void setLanguage (Language language)
{
m_language = language;
} // setLanguage
/**
* Set Display Mode of toString()
* @param displayMode DISPLAY_
*/
public void setDisplay (int displayMode)
{
m_displayMode = displayMode;
} // setDisplay
/**
* String representation
* @return info
*/
public String toString()
{
if (m_displayMode == DISPLAY_TIME_FROM)
return getInfoTimeFrom();
else if (m_displayMode == DISPLAY_TIME_FROM_TO)
return getInfoTimeFromTo();
else if (m_displayMode == DISPLAY_DATETIME_FROM_TO)
return getInfoDateTimeFromTo();
else if (m_displayMode == DISPLAY_NAME)
return m_name;
else if (m_displayMode == DISPLAY_NAME_DESCRIPTION)
return getInfoNameDescription();
else if (m_displayMode == DISPLAY_FULL)
return getInfo();
// DISPLAY_ALL
StringBuffer sb = new StringBuffer("MAssignmentSlot[");
sb.append(m_startTime).append("-").append(m_endTime)
.append("-Status=").append(m_status).append(",Name=")
.append(m_name).append(",").append(m_description).append("]");
return sb.toString();
} // toString
/**
* Get Info with Time From
* @return info 00:00
*/
public String getInfoTimeFrom()
{
return m_language.getTimeFormat().format(m_startTime);
} // getInfoTimeFrom
/**
* Get Info with Time From-To
* @return info 00:00 - 01:00
*/
public String getInfoTimeFromTo()
{
StringBuffer sb = new StringBuffer();
sb.append(m_language.getTimeFormat().format(m_startTime))
.append(" - ")
.append(m_language.getTimeFormat().format(m_endTime));
return sb.toString();
} // getInfoTimeFromTo
/**
* Get Info with Date & Time From-To
* @return info 12/12/01 00:00 - 01:00 or 12/12/01 00:00 - 12/13/01 01:00
*/
public String getInfoDateTimeFromTo()
{
StringBuffer sb = new StringBuffer();
sb.append(m_language.getDateTimeFormat().format(m_startTime))
.append(" - ");
if (TimeUtil.isSameDay(m_startTime, m_endTime))
sb.append(m_language.getTimeFormat().format(m_endTime));
else
m_language.getDateTimeFormat().format(m_endTime);
return sb.toString();
}
/**
* Get Info with Name and optional Description
* @return Name (Description)
*/
public String getInfoNameDescription()
{
StringBuffer sb = new StringBuffer(m_name);
if (m_description.length() > 0)
sb.append(" (").append(m_description).append(")");
return sb.toString();
} // getInfoNameDescription
/**
* Get Info with Date, Time From-To Name Description
* @return 12/12/01 00:00 - 01:00: Name (Description)
*/
public String getInfo()
{
StringBuffer sb = new StringBuffer(getInfoDateTimeFromTo());
sb.append(": ").append(m_name);
if (m_description.length() > 0)
sb.append(" (").append(m_description).append(")");
return sb.toString();
} // getInfo
/*************************************************************************/
/**
* Returns true if time is between start and end Time.
* Date part is ignored.
* <pre>
* Example:
* - Slots: 0:00-9:00 - 9:00-10:00 - 10:00-11:00 - ...
* - inSlot (9:00, false) -> 1 // start time
* - inSlot (10:00, true) -> 1 // end time
* </pre>
* @param time time of the day
* @param endTime if true, the end time is included
* @return true if within slot
*/
public boolean inSlot (Timestamp time, boolean endTime)
{
// Compare --
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(time);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.DAY_OF_YEAR, 1);
// handle -00:00 (end time)
if (endTime && cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) == 0)
{
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
}
Time compare = new Time (cal.getTimeInMillis());
// Start Time --
cal.setTime(m_startTime);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.DAY_OF_YEAR, 1);
Time start = new Time (cal.getTimeInMillis());
// End time --
cal.setTime(m_endTime);
cal.set(Calendar.YEAR, 1970);
cal.set(Calendar.DAY_OF_YEAR, 1);
if (cal.get(Calendar.HOUR_OF_DAY) == 0 && cal.get(Calendar.MINUTE) == 0)
{
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
}
Time end = new Time (cal.getTimeInMillis());
// before start x |---|
if (compare.before(start))
{
// System.out.println("InSlot-false Compare=" + compare + " before start " + start);
return false;
}
// after end |---| x
if (compare.after(end))
{
// System.out.println("InSlot-false Compare=" + compare + " after end " + end);
return false;
}
// start x---|
if (!endTime && compare.equals(start))
{
// System.out.println("InSlot-true Compare=" + compare + " = Start=" + start);
return true;
}
//
// end |---x
if (endTime && compare.equals(end))
{
// System.out.println("InSlot-true Compare=" + compare + " = End=" + end);
return true;
}
// between start/end |-x-|
if (compare.before(end))
{
// System.out.println("InSlot-true Compare=" + compare + " before end " + end);
return true;
}
return false;
} // inSlot
/*************************************************************************/
/**
* Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.
*
* @param o1 the first object to be compared.
* @param o2 the second object to be compared.
* @return a negative integer, zero, or a positive integer as the
* first argument is less than, equal to, or greater than the
* second.
* @throws ClassCastException if the arguments' types prevent them from
* being compared by this Comparator.
*/
public int compare(Object o1, Object o2)
{
if (!(o1 instanceof MAssignmentSlot && o2 instanceof MAssignmentSlot))
throw new ClassCastException ("MAssignmentSlot.compare arguments not MAssignmentSlot");
MAssignmentSlot s1 = (MAssignmentSlot)o1;
MAssignmentSlot s2 = (MAssignmentSlot)o2;
// Start Date
int result = s1.getStartTime().compareTo(s2.getStartTime());
if (result != 0)
return result;
// Status
result = s2.getStatus() - s1.getStatus();
if (result != 0)
return result;
// End Date
result = s1.getEndTime().compareTo(s2.getEndTime());
if (result != 0)
return result;
// Name
result = s1.getName().compareTo(s2.getName());
if (result != 0)
return result;
// Description
return s1.getDescription().compareTo(s2.getDescription());
} // compare
/**
* Indicates whether some other object is &quot;equal to&quot; this
* Comparator.
* @param obj the reference object with which to compare.
* @return <code>true</code> only if the specified object is also
* a comparator and it imposes the same ordering as this
* comparator.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.Object#hashCode()
*/
public boolean equals(Object obj)
{
if (obj instanceof MAssignmentSlot)
{
MAssignmentSlot cmp = (MAssignmentSlot)obj;
if (m_startTime.equals(cmp.getStartTime())
&& m_endTime.equals(cmp.getEndTime())
&& m_status == cmp.getStatus()
&& m_name.equals(cmp.getName())
&& m_description.equals(cmp.getDescription()))
return true;
}
return false;
} // equals
/**
* HashCode of MAssignmentSlot
* @return has code
*/
public int hashCode()
{
return m_startTime.hashCode() + m_endTime.hashCode() + m_status
+ m_name.hashCode() + m_description.hashCode();
} // hashCode
} // MAssignmentSlot

View File

@ -0,0 +1,312 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Product Attribute
*
* @author Jorg Janke
* @version $Id: MAttribute.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAttribute extends X_M_Attribute
{
/**
* Get Attributes Of Client
* @param ctx Properties
* @param onlyProductAttributes only Product Attributes
* @param onlyListAttributes only List Attributes
* @return array of attributes
*/
public static MAttribute[] getOfClient(Properties ctx,
boolean onlyProductAttributes, boolean onlyListAttributes)
{
ArrayList<MAttribute> list = new ArrayList<MAttribute>();
int AD_Client_ID = Env.getAD_Client_ID(ctx);
String sql = "SELECT * FROM M_Attribute "
+ "WHERE AD_Client_ID=? AND IsActive='Y'";
if (onlyProductAttributes)
sql += " AND IsInstanceAttribute='N'";
if (onlyListAttributes)
sql += " AND AttributeValueType='L'";
sql += " ORDER BY Name";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MAttribute (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;
}
MAttribute[] retValue = new MAttribute[list.size ()];
list.toArray (retValue);
s_log.fine("AD_Client_ID=" + AD_Client_ID + " - #" + retValue.length);
return retValue;
} // getOfClient
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MAttribute.class);
/**
* Standard Constructor
* @param ctx context
* @param M_Attribute_ID id
* @param trxName transaction
*/
public MAttribute (Properties ctx, int M_Attribute_ID, String trxName)
{
super (ctx, M_Attribute_ID, trxName);
if (M_Attribute_ID == 0)
{
setAttributeValueType(ATTRIBUTEVALUETYPE_StringMax40);
setIsInstanceAttribute (false);
setIsMandatory (false);
}
} // MAttribute
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttribute (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttribute
/** Values */
private MAttributeValue[] m_values = null;
/**
* Get Values if List
* @return Values or null if not list
*/
public MAttributeValue[] getMAttributeValues()
{
if (m_values == null && ATTRIBUTEVALUETYPE_List.equals(getAttributeValueType()))
{
ArrayList<MAttributeValue> list = new ArrayList<MAttributeValue>();
if (!isMandatory())
list.add (null);
//
String sql = "SELECT * FROM M_AttributeValue "
+ "WHERE M_Attribute_ID=? "
+ "ORDER BY Value";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, getM_Attribute_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add(new MAttributeValue (getCtx(), rs, null));
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
log.log(Level.SEVERE, sql, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
m_values = new MAttributeValue[list.size()];
list.toArray(m_values);
}
return m_values;
} // getValues
/**************************************************************************
* Get Attribute Instance
* @param M_AttributeSetInstance_ID attribute set instance
* @return Attribute Instance or null
*/
public MAttributeInstance getMAttributeInstance (int M_AttributeSetInstance_ID)
{
MAttributeInstance retValue = null;
String sql = "SELECT * "
+ "FROM M_AttributeInstance "
+ "WHERE M_Attribute_ID=? AND M_AttributeSetInstance_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getM_Attribute_ID());
pstmt.setInt(2, M_AttributeSetInstance_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
retValue = new MAttributeInstance (getCtx(), rs, get_TrxName());
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (SQLException ex)
{
log.log(Level.SEVERE, sql, ex);
}
try
{
if (pstmt != null)
pstmt.close ();
}
catch (SQLException ex1)
{
}
pstmt = null;
return retValue;
} // getAttributeInstance
/**
* Set Attribute Instance
* @param value value
* @param M_AttributeSetInstance_ID id
*/
public void setMAttributeInstance (int M_AttributeSetInstance_ID, MAttributeValue value)
{
MAttributeInstance instance = getMAttributeInstance(M_AttributeSetInstance_ID);
if (instance == null)
{
if (value != null)
instance = new MAttributeInstance (getCtx (), getM_Attribute_ID (),
M_AttributeSetInstance_ID, value.getM_AttributeValue_ID (),
value.getName (), get_TrxName()); // Cached !!
else
instance = new MAttributeInstance (getCtx(), getM_Attribute_ID(),
M_AttributeSetInstance_ID, 0, null, get_TrxName());
}
else
{
if (value != null)
{
instance.setM_AttributeValue_ID (value.getM_AttributeValue_ID ());
instance.setValue (value.getName()); // Cached !!
}
else
{
instance.setM_AttributeValue_ID (0);
instance.setValue (null);
}
}
instance.save();
} // setAttributeInstance
/**
* Set Attribute Instance
* @param value string value
* @param M_AttributeSetInstance_ID id
*/
public void setMAttributeInstance (int M_AttributeSetInstance_ID, String value)
{
MAttributeInstance instance = getMAttributeInstance(M_AttributeSetInstance_ID);
if (instance == null)
instance = new MAttributeInstance (getCtx(), getM_Attribute_ID(),
M_AttributeSetInstance_ID, value, get_TrxName());
else
instance.setValue(value);
instance.save();
} // setAttributeInstance
/**
* Set Attribute Instance
* @param value number value
* @param M_AttributeSetInstance_ID id
*/
public void setMAttributeInstance (int M_AttributeSetInstance_ID, BigDecimal value)
{
MAttributeInstance instance = getMAttributeInstance(M_AttributeSetInstance_ID);
if (instance == null)
instance = new MAttributeInstance (getCtx(), getM_Attribute_ID(),
M_AttributeSetInstance_ID, value, get_TrxName());
else
instance.setValueNumber(value);
instance.save();
} // setAttributeInstance
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAttribute[");
sb.append (get_ID()).append ("-").append (getName())
.append(",Type=").append(getAttributeValueType())
.append(",Instance=").append(isInstanceAttribute())
.append ("]");
return sb.toString ();
} // toString
/**
* AfterSave
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
// Changed to Instance Attribute
if (!newRecord && is_ValueChanged("IsInstanceAttribute") && isInstanceAttribute())
{
String sql = "UPDATE M_AttributeSet mas "
+ "SET IsInstanceAttribute='Y' "
+ "WHERE IsInstanceAttribute='N'"
+ " AND EXISTS (SELECT * FROM M_AttributeUse mau "
+ "WHERE mas.M_AttributeSet_ID=mau.M_AttributeSet_ID"
+ " AND mau.M_Attribute_ID=" + getM_Attribute_ID() + ")";
int no = DB.executeUpdate(sql, get_TrxName());
log.fine("AttributeSet Instance set #" + no);
}
return success;
} // afterSave
} // MAttribute

View File

@ -0,0 +1,161 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
/**
* Product Attribute Set
*
* @author Jorg Janke
* @version $Id: MAttributeInstance.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAttributeInstance extends X_M_AttributeInstance
{
/**
* Persistency Constructor
* @param ctx context
* @param ignored ignored
* @param trxName transaction
*/
public MAttributeInstance (Properties ctx, int ignored, String trxName)
{
super(ctx, 0, trxName);
if (ignored != 0)
throw new IllegalArgumentException("Multi-Key");
} // MAttributeInstance
/**
* Load Cosntructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttributeInstance (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttributeInstance
/**
* String Value Constructior
* @param ctx context
* @param M_Attribute_ID attribute
* @param M_AttributeSetInstance_ID instance
* @param Value string value
* @param trxName transaction
*/
public MAttributeInstance (Properties ctx, int M_Attribute_ID,
int M_AttributeSetInstance_ID, String Value, String trxName)
{
super(ctx, 0, trxName);
setM_Attribute_ID (M_Attribute_ID);
setM_AttributeSetInstance_ID (M_AttributeSetInstance_ID);
setValue (Value);
} // MAttributeInstance
/**
* Number Value Constructior
* @param ctx context
* @param M_Attribute_ID attribute
* @param M_AttributeSetInstance_ID instance
* @param BDValue number value
* @param trxName transaction
*/
public MAttributeInstance (Properties ctx, int M_Attribute_ID,
int M_AttributeSetInstance_ID, BigDecimal BDValue, String trxName)
{
super(ctx, 0, trxName);
setM_Attribute_ID (M_Attribute_ID);
setM_AttributeSetInstance_ID (M_AttributeSetInstance_ID);
setValueNumber(BDValue);
} // MAttributeInstance
/**
* Selection Value Constructior
* @param ctx context
* @param M_Attribute_ID attribute
* @param M_AttributeSetInstance_ID instance
* @param M_AttributeValue_ID selection
* @param Value String representation for fast display
* @param trxName transaction
*/
public MAttributeInstance (Properties ctx, int M_Attribute_ID,
int M_AttributeSetInstance_ID, int M_AttributeValue_ID, String Value, String trxName)
{
super(ctx, 0, trxName);
setM_Attribute_ID (M_Attribute_ID);
setM_AttributeSetInstance_ID (M_AttributeSetInstance_ID);
setM_AttributeValue_ID (M_AttributeValue_ID);
setValue (Value);
} // MAttributeInstance
/**
* Set ValueNumber
* @param ValueNumber number
*/
public void setValueNumber (BigDecimal ValueNumber)
{
super.setValueNumber (ValueNumber);
if (ValueNumber == null)
{
setValue(null);
return;
}
if (ValueNumber.signum() == 0)
{
setValue("0");
return;
}
// Display number w/o decimal 0
char[] chars = ValueNumber.toString().toCharArray();
StringBuffer display = new StringBuffer();
boolean add = false;
for (int i = chars.length-1; i >= 0; i--)
{
char c = chars[i];
if (add)
display.insert(0, c);
else
{
if (c == '0')
continue;
else if (c == '.') // decimal point
add = true;
else
{
display.insert(0, c);
add = true;
}
}
}
setValue(display.toString());
} // setValueNumber
/**
* String Representation
* @return info
*/
public String toString()
{
return getValue();
} // toString
} // MAttributeInstance

View File

@ -0,0 +1,489 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Product Attribute Set
*
* @author Jorg Janke
* @version $Id: MAttributeSet.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MAttributeSet extends X_M_AttributeSet
{
/**
* Get MAttributeSet from Cache
* @param ctx context
* @param M_AttributeSet_ID id
* @return MAttributeSet
*/
public static MAttributeSet get (Properties ctx, int M_AttributeSet_ID)
{
Integer key = new Integer (M_AttributeSet_ID);
MAttributeSet retValue = (MAttributeSet) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MAttributeSet (ctx, M_AttributeSet_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MAttributeSet> s_cache
= new CCache<Integer,MAttributeSet> ("M_AttributeSet", 20);
/**
* Standard constructor
* @param ctx context
* @param M_AttributeSet_ID id
* @param trxName transaction
*/
public MAttributeSet (Properties ctx, int M_AttributeSet_ID, String trxName)
{
super (ctx, M_AttributeSet_ID, trxName);
if (M_AttributeSet_ID == 0)
{
// setName (null);
setIsGuaranteeDate (false);
setIsGuaranteeDateMandatory (false);
setIsLot (false);
setIsLotMandatory (false);
setIsSerNo (false);
setIsSerNoMandatory (false);
setIsInstanceAttribute(false);
setMandatoryType (MANDATORYTYPE_NotMandatary);
}
} // MAttributeSet
/**
* Load constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttributeSet (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttributeSet
/** Instance Attributes */
private MAttribute[] m_instanceAttributes = null;
/** Instance Attributes */
private MAttribute[] m_productAttributes = null;
/** Entry Exclude */
private X_M_AttributeSetExclude[] m_excludes = null;
/** Lot create Exclude */
private X_M_LotCtlExclude[] m_excludeLots = null;
/** Serial No create Exclude */
private X_M_SerNoCtlExclude[] m_excludeSerNos = null;
/**
* Get Attribute Array
* @param instanceAttributes true if for instance
* @return instance or product attribute array
*/
public MAttribute[] getMAttributes (boolean instanceAttributes)
{
if ((m_instanceAttributes == null && instanceAttributes)
|| m_productAttributes == null && !instanceAttributes)
{
String sql = "SELECT mau.M_Attribute_ID "
+ "FROM M_AttributeUse mau"
+ " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
+ "WHERE mau.IsActive='Y' AND ma.IsActive='Y'"
+ " AND mau.M_AttributeSet_ID=? AND ma.IsInstanceAttribute=? " // #1,2
+ "ORDER BY mau.SeqNo";
ArrayList<MAttribute> list = new ArrayList<MAttribute>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, getM_AttributeSet_ID());
pstmt.setString(2, instanceAttributes ? "Y" : "N");
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
MAttribute ma = new MAttribute (getCtx(), rs.getInt(1), get_TrxName());
list.add (ma);
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
log.log(Level.SEVERE, sql, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
// Differentiate attributes
if (instanceAttributes)
{
m_instanceAttributes = new MAttribute[list.size()];
list.toArray (m_instanceAttributes);
}
else
{
m_productAttributes = new MAttribute[list.size()];
list.toArray (m_productAttributes);
}
}
//
if (instanceAttributes)
{
if (isInstanceAttribute() != m_instanceAttributes.length > 0)
setIsInstanceAttribute(m_instanceAttributes.length > 0);
}
// Return
if (instanceAttributes)
return m_instanceAttributes;
return m_productAttributes;
} // getMAttributes
/**
* Something is Mandatory
* @return true if something is mandatory
*/
public boolean isMandatory()
{
return !MANDATORYTYPE_NotMandatary.equals(getMandatoryType())
|| isLotMandatory()
|| isSerNoMandatory()
|| isGuaranteeDateMandatory();
} // isMandatory
/**
* Is always mandatory
* @return mandatory
*/
public boolean isMandatoryAlways()
{
return MANDATORYTYPE_AlwaysMandatory.equals(getMandatoryType());
} // isMandatoryAlways
/**
* Is Mandatory when Shipping
* @return true if required for shipping
*/
public boolean isMandatoryShipping()
{
return MANDATORYTYPE_WhenShipping.equals(getMandatoryType());
} // isMandatoryShipping
/**
* Exclude entry
* @param AD_Column_ID column
* @param isSOTrx sales order
* @return true if excluded
*/
public boolean excludeEntry (int AD_Column_ID, boolean isSOTrx)
{
if (m_excludes == null)
{
ArrayList<X_M_AttributeSetExclude> list = new ArrayList<X_M_AttributeSetExclude>();
String sql = "SELECT * FROM M_AttributeSetExclude WHERE IsActive='Y' AND M_AttributeSet_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getM_AttributeSet_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new X_M_AttributeSetExclude (getCtx(), 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;
}
m_excludes = new X_M_AttributeSetExclude[list.size ()];
list.toArray (m_excludes);
}
// Find it
if (m_excludes != null && m_excludes.length > 0)
{
MColumn column = MColumn.get(getCtx(), AD_Column_ID);
for (int i = 0; i < m_excludes.length; i++)
{
if (m_excludes[i].getAD_Table_ID() == column.getAD_Table_ID()
&& m_excludes[i].isSOTrx() == isSOTrx)
return true;
}
}
return false;
} // excludeEntry
/**
* Exclude Lot creation
* @param AD_Column_ID column
* @param isSOTrx SO
* @return true if excluded
*/
public boolean isExcludeLot (int AD_Column_ID, boolean isSOTrx)
{
if (getM_LotCtl_ID() == 0)
return true;
if (m_excludeLots == null)
{
ArrayList<X_M_LotCtlExclude> list = new ArrayList<X_M_LotCtlExclude>();
String sql = "SELECT * FROM M_LotCtlExclude WHERE IsActive='Y' AND M_LotCtl_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getM_LotCtl_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new X_M_LotCtlExclude (getCtx(), 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;
}
m_excludeLots = new X_M_LotCtlExclude[list.size ()];
list.toArray (m_excludeLots);
}
// Find it
if (m_excludeLots != null && m_excludeLots.length > 0)
{
MColumn column = MColumn.get(getCtx(), AD_Column_ID);
for (int i = 0; i < m_excludeLots.length; i++)
{
if (m_excludeLots[i].getAD_Table_ID() == column.getAD_Table_ID()
&& m_excludeLots[i].isSOTrx() == isSOTrx)
return true;
}
}
return false;
} // isExcludeLot
/**
* Exclude SerNo creation
* @param AD_Column_ID column
* @param isSOTrx SO
* @return true if excluded
*/
public boolean isExcludeSerNo (int AD_Column_ID, boolean isSOTrx)
{
if (getM_SerNoCtl_ID() == 0)
return true;
if (m_excludeSerNos == null)
{
ArrayList<X_M_SerNoCtlExclude> list = new ArrayList<X_M_SerNoCtlExclude>();
String sql = "SELECT * FROM M_SerNoCtlExclude WHERE IsActive='Y' AND M_SerNoCtl_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, getM_SerNoCtl_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new X_M_SerNoCtlExclude (getCtx(), 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;
}
m_excludeSerNos = new X_M_SerNoCtlExclude[list.size ()];
list.toArray (m_excludeSerNos);
}
// Find it
if (m_excludeSerNos != null && m_excludeSerNos.length > 0)
{
MColumn column = MColumn.get(getCtx(), AD_Column_ID);
for (int i = 0; i < m_excludeSerNos.length; i++)
{
if (m_excludeSerNos[i].getAD_Table_ID() == column.getAD_Table_ID()
&& m_excludeSerNos[i].isSOTrx() == isSOTrx)
return true;
}
}
return false;
} // isExcludeSerNo
/**
* Get Lot Char Start
* @return defined or \u00ab
*/
public String getLotCharStart()
{
String s = super.getLotCharSOverwrite ();
if (s != null && s.length() == 1 && !s.equals(" "))
return s;
return "\u00ab";
} // getLotCharStart
/**
* Get Lot Char End
* @return defined or \u00bb
*/
public String getLotCharEnd()
{
String s = super.getLotCharEOverwrite ();
if (s != null && s.length() == 1 && !s.equals(" "))
return s;
return "\u00bb";
} // getLotCharEnd
/**
* Get SerNo Char Start
* @return defined or #
*/
public String getSerNoCharStart()
{
String s = super.getSerNoCharSOverwrite ();
if (s != null && s.length() == 1 && !s.equals(" "))
return s;
return "#";
} // getSerNoCharStart
/**
* Get SerNo Char End
* @return defined or none
*/
public String getSerNoCharEnd()
{
String s = super.getSerNoCharEOverwrite ();
if (s != null && s.length() == 1 && !s.equals(" "))
return s;
return "";
} // getSerNoCharEnd
/**
* Before Save.
* - set instance attribute flag
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (!isInstanceAttribute()
&& (isSerNo() || isLot() || isGuaranteeDate()) )
setIsInstanceAttribute(true);
return true;
} // beforeSave
/**
* After Save.
* - Verify Instance Attribute
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
// Set Instance Attribute
if (!isInstanceAttribute())
{
String sql = "UPDATE M_AttributeSet mas"
+ " SET IsInstanceAttribute='Y' "
+ "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID()
+ " AND IsInstanceAttribute='N'"
+ " AND (IsSerNo='Y' OR IsLot='Y' OR IsGuaranteeDate='Y'"
+ " OR EXISTS (SELECT * FROM M_AttributeUse mau"
+ " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
+ "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
+ " AND mau.IsActive='Y' AND ma.IsActive='Y'"
+ " AND ma.IsInstanceAttribute='Y')"
+ ")";
int no = DB.executeUpdate(sql, get_TrxName());
if (no != 0)
{
log.warning("Set Instance Attribute");
setIsInstanceAttribute(true);
}
}
// Reset Instance Attribute
if (isInstanceAttribute() && !isSerNo() && !isLot() && !isGuaranteeDate())
{
String sql = "UPDATE M_AttributeSet mas"
+ " SET IsInstanceAttribute='N' "
+ "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID()
+ " AND IsInstanceAttribute='Y'"
+ " AND IsSerNo='N' AND IsLot='N' AND IsGuaranteeDate='N'"
+ " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau"
+ " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
+ "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
+ " AND mau.IsActive='Y' AND ma.IsActive='Y'"
+ " AND ma.IsInstanceAttribute='Y')";
int no = DB.executeUpdate(sql, get_TrxName());
if (no != 0)
{
log.warning("Reset Instance Attribute");
setIsInstanceAttribute(false);
}
}
return success;
} // afterSave
} // MAttributeSet

View File

@ -0,0 +1,342 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Product Attribute Set Instance
*
* @author Jorg Janke
* @version $Id: MAttributeSetInstance.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAttributeSetInstance extends X_M_AttributeSetInstance
{
/**
* Get Attribute Set Instance from ID or Product
* @param ctx context
* @param M_AttributeSetInstance_ID id or 0
* @param M_Product_ID required if id is 0
* @return Attribute Set Instance or null
*/
public static MAttributeSetInstance get (Properties ctx,
int M_AttributeSetInstance_ID, int M_Product_ID)
{
MAttributeSetInstance retValue = null;
// Load Instance if not 0
if (M_AttributeSetInstance_ID != 0)
{
s_log.fine("From M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID);
return new MAttributeSetInstance (ctx, M_AttributeSetInstance_ID, null);
}
// Get new from Product
s_log.fine("From M_Product_ID=" + M_Product_ID);
if (M_Product_ID == 0)
return null;
String sql = "SELECT M_AttributeSet_ID, M_AttributeSetInstance_ID "
+ "FROM M_Product "
+ "WHERE M_Product_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
int M_AttributeSet_ID = rs.getInt(1);
// M_AttributeSetInstance_ID = rs.getInt(2); // needed ?
//
retValue = new MAttributeSetInstance (ctx, 0, M_AttributeSet_ID, null);
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
s_log.log(Level.SEVERE, sql, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
//
return retValue;
} // get
private static CLogger s_log = CLogger.getCLogger (MAttributeSetInstance.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param M_AttributeSetInstance_ID id
* @param trxName transaction
*/
public MAttributeSetInstance (Properties ctx, int M_AttributeSetInstance_ID, String trxName)
{
super (ctx, M_AttributeSetInstance_ID, trxName);
if (M_AttributeSetInstance_ID == 0)
{
}
} // MAttributeSetInstance
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttributeSetInstance (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttributeSetInstance
/**
* Standard Constructor
* @param ctx context
* @param M_AttributeSetInstance_ID id
* @param M_AttributeSet_ID attribute set
* @param trxName transaction
*/
public MAttributeSetInstance (Properties ctx, int M_AttributeSetInstance_ID,
int M_AttributeSet_ID, String trxName)
{
this (ctx, M_AttributeSetInstance_ID, trxName);
setM_AttributeSet_ID(M_AttributeSet_ID);
} // MAttributeSetInstance
/** Attribute Set */
private MAttributeSet m_mas = null;
/** Date Format */
private DateFormat m_dateFormat = DisplayType.getDateFormat(DisplayType.Date);
/**
* Set Attribute Set
* @param mas attribute set
*/
public void setMAttributeSet (MAttributeSet mas)
{
m_mas = mas;
setM_AttributeSet_ID(mas.getM_AttributeSet_ID());
} // setAttributeSet
/**
* Get Attribute Set
* @return Attrbute Set or null
*/
public MAttributeSet getMAttributeSet()
{
if (m_mas == null && getM_AttributeSet_ID() != 0)
m_mas = new MAttributeSet (getCtx(), getM_AttributeSet_ID(), get_TrxName());
return m_mas;
} // getMAttributeSet
/**
* Set Description.
* - Product Values
* - Instance Values
* - SerNo = #123
* - Lot = \u00ab123\u00bb
* - GuaranteeDate = 10/25/2003
*/
public void setDescription()
{
// Make sure we have a Attribute Set
getMAttributeSet();
if (m_mas == null)
{
setDescription ("");
return;
}
StringBuffer sb = new StringBuffer();
// Instance Attribute Values
MAttribute[] attributes = m_mas.getMAttributes(true);
for (int i = 0; i < attributes.length; i++)
{
MAttributeInstance mai = attributes[i].getMAttributeInstance(getM_AttributeSetInstance_ID());
if (mai != null && mai.getValue() != null)
{
if (sb.length() > 0)
sb.append("_");
sb.append(mai.getValue());
}
}
// SerNo
if (m_mas.isSerNo() && getSerNo() != null)
{
if (sb.length() > 0)
sb.append("_");
sb.append(m_mas.getSerNoCharStart()).append(getSerNo()).append(m_mas.getSerNoCharEnd());
}
// Lot
if (m_mas.isLot() && getLot() != null)
{
if (sb.length() > 0)
sb.append("_");
sb.append(m_mas.getLotCharStart()).append(getLot()).append(m_mas.getLotCharEnd());
}
// GuaranteeDate
if (m_mas.isGuaranteeDate() && getGuaranteeDate() != null)
{
if (sb.length() > 0)
sb.append("_");
sb.append (m_dateFormat.format(getGuaranteeDate()));
}
// Product Attribute Values
attributes = m_mas.getMAttributes(false);
for (int i = 0; i < attributes.length; i++)
{
MAttributeInstance mai = attributes[i].getMAttributeInstance(getM_AttributeSetInstance_ID());
if (mai != null && mai.getValue() != null)
{
if (sb.length() > 0)
sb.append("_");
sb.append(mai.getValue());
}
}
setDescription (sb.toString());
} // setDescription
/**
* Get Guarantee Date
* @param getNew if true calculates/sets guarantee date
* @return guarantee date or null if days = 0
*/
public Timestamp getGuaranteeDate(boolean getNew)
{
if (getNew)
{
int days = getMAttributeSet().getGuaranteeDays();
if (days > 0)
{
Timestamp ts = TimeUtil.addDays(new Timestamp(System.currentTimeMillis()), days);
setGuaranteeDate(ts);
}
}
return getGuaranteeDate();
} // getGuaranteeDate
/**
* Get Lot No
* @param getNew if true create/set new lot
* @param M_Product_ID product used if new
* @return lot
*/
public String getLot (boolean getNew, int M_Product_ID)
{
if (getNew)
createLot(M_Product_ID);
return getLot();
} // getLot
/**
* Create Lot
* @param M_Product_ID product used if new
* @return lot info
*/
public KeyNamePair createLot (int M_Product_ID)
{
KeyNamePair retValue = null;
int M_LotCtl_ID = getMAttributeSet().getM_LotCtl_ID();
if (M_LotCtl_ID != 0)
{
MLotCtl ctl = new MLotCtl (getCtx(), M_LotCtl_ID, null);
MLot lot = ctl.createLot(M_Product_ID);
setM_Lot_ID (lot.getM_Lot_ID());
setLot (lot.getName());
retValue = new KeyNamePair (lot.getM_Lot_ID(), lot.getName());
}
return retValue;
} // createLot
/**
* To to find lot and set Lot/ID
* @param Lot lot
* @param M_Product_ID product
*/
public void setLot (String Lot, int M_Product_ID)
{
// Try to find it
MLot mLot = MLot.getProductLot(getCtx(), M_Product_ID, Lot, get_TrxName());
if (mLot != null)
setM_Lot_ID(mLot.getM_Lot_ID());
setLot (Lot);
} // setLot
/**
* Exclude Lot creation
* @param AD_Column_ID column
* @param isSOTrx SO
* @return true if excluded
*/
public boolean isExcludeLot (int AD_Column_ID, boolean isSOTrx)
{
getMAttributeSet();
if (m_mas != null)
return m_mas.isExcludeLot (AD_Column_ID, isSOTrx);
return false;
} // isExcludeLot
/**
* Get Serial No
* @param getNew if true create/set new Ser No
* @return Serial Number
*/
public String getSerNo (boolean getNew)
{
if (getNew)
{
int M_SerNoCtl_ID = getMAttributeSet().getM_SerNoCtl_ID();
if (M_SerNoCtl_ID != 0)
{
MSerNoCtl ctl = new MSerNoCtl (getCtx(), M_SerNoCtl_ID, get_TrxName());
setSerNo(ctl.createSerNo());
}
}
return getSerNo();
} // getSerNo
/**
* Exclude SerNo creation
* @param AD_Column_ID column
* @param isSOTrx SO
* @return true if excluded
*/
public boolean isExcludeSerNo (int AD_Column_ID, boolean isSOTrx)
{
getMAttributeSet();
if (m_mas != null)
return m_mas.isExcludeSerNo (AD_Column_ID, isSOTrx);
return false;
} // isExcludeSerNo
} // MAttributeSetInstance

View File

@ -0,0 +1,110 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Attribute Use Model
*
* @author Jorg Janke
* @version $Id: MAttributeUse.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MAttributeUse extends X_M_AttributeUse
{
/**
* Persistency Constructor
* @param ctx context
* @param ignored ignored
* @param trxName transaction
*/
public MAttributeUse (Properties ctx, int ignored, String trxName)
{
super (ctx, ignored, trxName);
if (ignored != 0)
throw new IllegalArgumentException("Multi-Key");
} // MAttributeUse
/**
* Load Cosntructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttributeUse (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttributeUse
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
// also used for afterDelete
String sql = "UPDATE M_AttributeSet mas"
+ " SET IsInstanceAttribute='Y' "
+ "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID()
+ " AND IsInstanceAttribute='N'"
+ " AND (IsSerNo='Y' OR IsLot='Y' OR IsGuaranteeDate='Y'"
+ " OR EXISTS (SELECT * FROM M_AttributeUse mau"
+ " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
+ "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
+ " AND mau.IsActive='Y' AND ma.IsActive='Y'"
+ " AND ma.IsInstanceAttribute='Y')"
+ ")";
int no = DB.executeUpdate(sql, get_TrxName());
if (no != 0)
log.fine("afterSave - Set Instance Attribute");
//
sql = "UPDATE M_AttributeSet mas"
+ " SET IsInstanceAttribute='N' "
+ "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID()
+ " AND IsInstanceAttribute='Y'"
+ " AND IsSerNo='N' AND IsLot='N' AND IsGuaranteeDate='N'"
+ " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau"
+ " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
+ "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
+ " AND mau.IsActive='Y' AND ma.IsActive='Y'"
+ " AND ma.IsInstanceAttribute='Y')";
no = DB.executeUpdate(sql, get_TrxName());
if (no != 0)
log.fine("afterSave - Reset Instance Attribute");
return success;
} // afterSave
/**
* After Delete
* @param success success
* @return success
*/
protected boolean afterDelete (boolean success)
{
afterSave(false, success);
return success;
} // afterDelete
} // MAttributeUse

View File

@ -0,0 +1,69 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.util.*;
import java.sql.*;
/**
* Product Attribute Value
*
* @author Jorg Janke
* @version $Id: MAttributeValue.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MAttributeValue extends X_M_AttributeValue
{
/**
* Constructor
* @param ctx context
* @param M_AttributeValue_ID id
* @param trxName transaction
*/
public MAttributeValue (Properties ctx, int M_AttributeValue_ID, String trxName)
{
super (ctx, M_AttributeValue_ID, trxName);
/** if (M_AttributeValue_ID == 0)
{
setM_AttributeValue_ID (0);
setM_Attribute_ID (0);
setName (null);
setValue (null);
}
**/
} // MAttributeValue
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAttributeValue (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MAttributeValue
/**
* String Representation
* @return info
*/
public String toString()
{
return getName();
} // toString
} // MAttributeValue

View File

@ -0,0 +1,178 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* BOM Model
* @author Jorg Janke
* @version $Id: MBOM.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MBOM extends X_M_BOM
{
/**
* Get BOM from Cache
* @param ctx context
* @param M_BOM_ID id
* @return MBOM
*/
public static MBOM get (Properties ctx, int M_BOM_ID)
{
Integer key = new Integer (M_BOM_ID);
MBOM retValue = (MBOM) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MBOM (ctx, M_BOM_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/**
* Get BOMs Of Product
* @param ctx context
* @param M_Product_ID product
* @param trxName trx
* @param whereClause optional WHERE clause w/o AND
* @return array of BOMs
*/
public static MBOM[] getOfProduct (Properties ctx, int M_Product_ID,
String trxName, String whereClause)
{
ArrayList<MBOM> list = new ArrayList<MBOM>();
String sql = "SELECT * FROM M_BOM WHERE M_Product_ID=?";
if (whereClause != null && whereClause.length() > 0)
sql += " AND " + whereClause;
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, trxName);
pstmt.setInt (1, M_Product_ID);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MBOM (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;
}
MBOM[] retValue = new MBOM[list.size ()];
list.toArray (retValue);
return retValue;
} // getOfProduct
/** Cache */
private static CCache<Integer,MBOM> s_cache
= new CCache<Integer,MBOM>("M_BOM", 20);
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MBOM.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param M_BOM_ID id
* @param trxName trx
*/
public MBOM (Properties ctx, int M_BOM_ID, String trxName)
{
super (ctx, M_BOM_ID, trxName);
if (M_BOM_ID == 0)
{
// setM_Product_ID (0);
// setName (null);
setBOMType (BOMTYPE_CurrentActive); // A
setBOMUse (BOMUSE_Master); // A
}
} // MBOM
/**
* Load Constructor
* @param ctx ctx
* @param rs result set
* @param trxName trx
*/
public MBOM (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MBOM
/**
* Before Save
* @param newRecord new
* @return true/false
*/
protected boolean beforeSave (boolean newRecord)
{
// BOM Type
if (newRecord || is_ValueChanged("BOMType"))
{
// Only one Current Active
if (getBOMType().equals(BOMTYPE_CurrentActive))
{
MBOM[] boms = getOfProduct(getCtx(), getM_Product_ID(), get_TrxName(),
"BOMType='A' AND BOMUse='" + getBOMUse() + "' AND IsActive='Y'");
if (boms.length == 0 // only one = this
|| (boms.length == 1 && boms[0].getM_BOM_ID() == getM_BOM_ID()))
;
else
{
log.saveError("Error", Msg.parseTranslation(getCtx(),
"Can only have one Current Active BOM for Product BOM Use (" + getBOMType() + ")"));
return false;
}
}
// Only one MTO
else if (getBOMType().equals(BOMTYPE_Make_To_Order))
{
MBOM[] boms = getOfProduct(getCtx(), getM_Product_ID(), get_TrxName(),
"IsActive='Y'");
if (boms.length == 0 // only one = this
|| (boms.length == 1 && boms[0].getM_BOM_ID() == getM_BOM_ID()))
;
else
{
log.saveError("Error", Msg.parseTranslation(getCtx(),
"Can only have single Make-to-Order BOM for Product"));
return false;
}
}
} // BOM Type
return true;
} // beforeSave
} // MBOM

View File

@ -0,0 +1,215 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* BOM Product/Component Model
*
* @author Jorg Janke
* @version $Id: MBOMProduct.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MBOMProduct extends X_M_BOMProduct
{
/**
* Get Products of BOM
* @param bom bom
* @return array of BOM Products
*/
public static MBOMProduct[] getOfBOM (MBOM bom)
{
ArrayList<MBOMProduct> list = new ArrayList<MBOMProduct>();
String sql = "SELECT * FROM M_BOMProduct WHERE M_BOM_ID=? ORDER BY SeqNo";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, bom.get_TrxName());
pstmt.setInt (1, bom.getM_BOM_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MBOMProduct (bom.getCtx(), rs, bom.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;
}
MBOMProduct[] retValue = new MBOMProduct[list.size ()];
list.toArray (retValue);
return retValue;
} // getOfProduct
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MBOMProduct.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param M_BOMProduct_ID id
* @param trxName trx
*/
public MBOMProduct (Properties ctx, int M_BOMProduct_ID, String trxName)
{
super (ctx, M_BOMProduct_ID, trxName);
if (M_BOMProduct_ID == 0)
{
// setM_BOM_ID (0);
setBOMProductType (BOMPRODUCTTYPE_StandardProduct); // S
setBOMQty (Env.ONE);
setIsPhantom (false);
setLeadTimeOffset (0);
// setLine (0); // @SQL=SELECT NVL(MAX(Line),0)+10 AS DefaultValue FROM M_BOMProduct WHERE M_BOM_ID=@M_BOM_ID@
}
} // MBOMProduct
/**
* Parent Constructor
* @param bom product
*/
public MBOMProduct (MBOM bom)
{
this (bom.getCtx(), 0, bom.get_TrxName());
m_bom = bom;
} // MBOMProduct
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MBOMProduct (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MBOMProduct
/** BOM Parent */
private MBOM m_bom = null;
/**
* Get Parent
* @return parent
*/
private MBOM getBOM()
{
if (m_bom == null && getM_BOM_ID() != 0)
m_bom = MBOM.get(getCtx(), getM_BOM_ID());
return m_bom;
} // getBOM
/**
* Before Save
* @param newRecord new
* @return true/false
*/
protected boolean beforeSave (boolean newRecord)
{
// Product
if (getBOMProductType().equals(BOMPRODUCTTYPE_OutsideProcessing))
{
if (getM_ProductBOM_ID() != 0)
setM_ProductBOM_ID(0);
}
else if (getM_ProductBOM_ID() == 0)
{
log.saveError("Error", Msg.parseTranslation(getCtx(), "@NotFound@ @M_ProductBOM_ID@"));
return false;
}
// Operation
if (getM_ProductOperation_ID() == 0)
{
if (getSeqNo() != 0)
setSeqNo(0);
}
else if (getSeqNo() == 0)
{
log.saveError("Error", Msg.parseTranslation(getCtx(), "@NotFound@ @SeqNo@"));
return false;
}
// Product Attribute Instance
if (getM_AttributeSetInstance_ID() != 0)
{
getBOM();
if (m_bom != null
&& MBOM.BOMTYPE_Make_To_Order.equals(m_bom.getBOMType()))
;
else
{
log.saveError("Error", Msg.parseTranslation(getCtx(),
"Reset @M_AttributeSetInstance_ID@: Not Make-to-Order"));
setM_AttributeSetInstance_ID(0);
return false;
}
}
// Alternate
if ((getBOMProductType().equals(BOMPRODUCTTYPE_Alternative)
|| getBOMProductType().equals(BOMPRODUCTTYPE_AlternativeDefault))
&& getM_BOMAlternative_ID() == 0)
{
log.saveError("Error", Msg.parseTranslation(getCtx(), "@NotFound@ @M_BOMAlternative_ID@"));
return false;
}
// Operation
if (getM_ProductOperation_ID() != 0)
{
if (getSeqNo() == 0)
{
log.saveError("Error", Msg.parseTranslation(getCtx(), "@NotFound@ @SeqNo@"));
return false;
}
}
else // no op
{
if (getSeqNo() != 0)
setSeqNo(0);
if (getLeadTimeOffset() != 0)
setLeadTimeOffset(0);
}
// Set Line Number
if (getLine() == 0)
{
String sql = "SELECT NVL(MAX(Line),0)+10 FROM M_BOMProduct WHERE M_BOM_ID=?";
int ii = DB.getSQLValue (get_TrxName(), sql, getM_BOM_ID());
setLine (ii);
}
return true;
} // beforeSave
} // MBOMProduct

View File

@ -0,0 +1,97 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
/**
* BP Bank Account Model
*
* @author Jorg Janke
* @version $Id: MBPBankAccount.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MBPBankAccount extends X_C_BP_BankAccount
{
/**
* Constructor
* @param ctx context
* @param C_BP_BankAccount_ID BP bank account
* @param trxName transaction
*/
public MBPBankAccount (Properties ctx, int C_BP_BankAccount_ID, String trxName)
{
super (ctx, C_BP_BankAccount_ID, trxName);
if (C_BP_BankAccount_ID == 0)
{
// setC_BPartner_ID (0);
setIsACH (false);
}
} // MBP_BankAccount
/**
* Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBPBankAccount (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBP_BankAccount
/**
* Constructor
* @param ctx context
* @param bp BP
* @param bpc BP Contact
* @param location Location
*/
public MBPBankAccount (Properties ctx, MBPartner bp, MUser bpc, MLocation location)
{
super(ctx, 0, bp.get_TrxName());
setIsACH (false);
//
setC_BPartner_ID(bp.getC_BPartner_ID());
//
setA_Name(bpc.getName());
setA_EMail(bpc.getEMail());
//
setA_Street(location.getAddress1());
setA_City(location.getCity());
setA_Zip(location.getPostal());
setA_State(location.getRegionName(true));
setA_Country(location.getCountryName());
} // MBP_BankAccount
/*************************************************************************/
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MBP_BankAccount[")
.append (get_ID ())
.append(", Name=").append(getA_Name())
.append ("]");
return sb.toString ();
} // toString
} // MBPBankAccount

View File

@ -0,0 +1,245 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Business Partner Group Model
*
* @author Jorg Janke
* @version $Id: MBPGroup.java,v 1.4 2006/09/23 15:54:22 jjanke Exp $
*/
public class MBPGroup extends X_C_BP_Group
{
/**
* Get MBPGroup from Cache
* @param ctx context
* @param C_BP_Group_ID id
* @return MBPGroup
*/
public static MBPGroup get (Properties ctx, int C_BP_Group_ID)
{
Integer key = new Integer (C_BP_Group_ID);
MBPGroup retValue = (MBPGroup) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MBPGroup (ctx, C_BP_Group_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/**
* Get Default MBPGroup
* @param ctx context
* @return MBPGroup
*/
public static MBPGroup getDefault (Properties ctx)
{
int AD_Client_ID = Env.getAD_Client_ID(ctx);
Integer key = new Integer (AD_Client_ID);
MBPGroup retValue = (MBPGroup) s_cacheDefault.get (key);
if (retValue != null)
return retValue;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM C_BP_Group g "
+ "WHERE IsDefault='Y' AND AD_Client_ID=? "
+ "ORDER BY IsActive DESC";
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
{
retValue = new MBPGroup (ctx, rs, null);
if (retValue.get_ID () != 0)
s_cacheDefault.put (key, retValue);
}
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;
}
if (retValue == null)
s_log.warning("No Default BP Group for AD_Client_ID=" + AD_Client_ID);
return retValue;
} // get
/**
* Get MBPGroup from Business Partner
* @param ctx context
* @param C_BPartner_ID business partner id
* @return MBPGroup
*/
public static MBPGroup getOfBPartner (Properties ctx, int C_BPartner_ID)
{
MBPGroup retValue = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM C_BP_Group g "
+ "WHERE EXISTS (SELECT * FROM C_BPartner p "
+ "WHERE p.C_BPartner_ID=? AND p.C_BP_Group_ID=g.C_BP_Group_ID)";
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, C_BPartner_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
{
retValue = new MBPGroup (ctx, rs, null);
Integer key = new Integer (retValue.getC_BP_Group_ID());
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
}
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 retValue;
} // getOfBPartner
/** Cache */
private static CCache<Integer,MBPGroup> s_cache
= new CCache<Integer,MBPGroup>("BP_Group", 10);
/** Default Cache */
private static CCache<Integer,MBPGroup> s_cacheDefault
= new CCache<Integer,MBPGroup>("BP_Group", 5);
/** Logger */
private static CLogger s_log = CLogger.getCLogger (MBPGroup.class);
/**
* Standard Constructor
* @param ctx context
* @param C_BP_Group_ID id
* @param trxName transaction
*/
public MBPGroup (Properties ctx, int C_BP_Group_ID, String trxName)
{
super (ctx, C_BP_Group_ID, trxName);
if (C_BP_Group_ID == 0)
{
// setValue (null);
// setName (null);
setIsConfidentialInfo (false); // N
setIsDefault (false);
setPriorityBase(PRIORITYBASE_Same);
}
} // MBPGroup
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBPGroup (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBPGroup
/**
* Get Credit Watch Percent
* @return 90 or defined percent
*/
public BigDecimal getCreditWatchPercent ()
{
BigDecimal bd = super.getCreditWatchPercent();
if (bd != null)
return bd;
return new BigDecimal(90);
} // getCreditWatchPercent
/**
* Get Credit Watch Ratio
* @return 0.90 or defined percent
*/
public BigDecimal getCreditWatchRatio()
{
BigDecimal bd = super.getCreditWatchPercent();
if (bd != null)
return bd.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP);
return new BigDecimal(0.90);
} // getCreditWatchRatio
@Override
protected boolean beforeSave (boolean newRecord)
{
// TODO Auto-generated method stub
return true;
}
/**
* After Save
* @param newRecord new record
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord & success)
return insert_Accounting("C_BP_Group_Acct", "C_AcctSchema_Default", null);
return success;
} // afterSave
/**
* Before Delete
* @return true
*/
protected boolean beforeDelete ()
{
return delete_Accounting("C_BP_Group_Acct");
} // beforeDelete
} // MBPGroup

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,152 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Business Partner Info Model for Query
*
* @author Jorg Janke
* @version $Id: MBPartnerInfo.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MBPartnerInfo extends X_RV_BPartner
{
/**
* Find BPartners
* @param ctx context
* @param Value Business Partner Value
* @param Name Business Partner Name
* @param Contact Contact/User Name
* @param EMail Contact/User EMail
* @param Phone phone
* @param City city
* @return array if of info
*/
public static MBPartnerInfo[] find (Properties ctx,
String Value, String Name, String Contact, String EMail, String Phone, String City)
{
StringBuffer sql = new StringBuffer ("SELECT * FROM RV_BPartner WHERE IsActive='Y'");
StringBuffer sb = new StringBuffer();
Value = getFindParameter (Value);
if (Value != null)
sb.append("UPPER(Value) LIKE ?");
Name = getFindParameter (Name);
if (Name != null)
{
if (sb.length() > 0)
sb.append(" OR ");
sb.append("UPPER(Name) LIKE ?");
}
Contact = getFindParameter (Contact);
if (Contact != null)
{
if (sb.length() > 0)
sb.append(" OR ");
sb.append("UPPER(Contact) LIKE ?");
}
EMail = getFindParameter (EMail);
if (EMail != null)
{
if (sb.length() > 0)
sb.append(" OR ");
sb.append("UPPER(EMail) LIKE ?");
}
Phone = getFindParameter (Phone);
if (Phone != null)
{
if (sb.length() > 0)
sb.append(" OR ");
sb.append("UPPER(Phone) LIKE ?");
}
City = getFindParameter (City);
if (City != null)
{
if (sb.length() > 0)
sb.append(" OR ");
sb.append("UPPER(City) LIKE ?");
}
if (sb.length() > 0)
sql.append(" AND (").append(sb).append(")");
sql.append(" ORDER BY Value");
//
String finalSQL = MRole.getDefault().addAccessSQL(sql.toString(),
"RV_BPartner", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
ArrayList<MBPartnerInfo> list = new ArrayList<MBPartnerInfo>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(finalSQL, null);
int index = 1;
if (Value != null)
pstmt.setString(index++, Value);
if (Name != null)
pstmt.setString(index++, Name);
if (Contact != null)
pstmt.setString(index++, Contact);
if (EMail != null)
pstmt.setString(index++, EMail);
if (Phone != null)
pstmt.setString(index++, Phone);
if (City != null)
pstmt.setString(index++, City);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add(new MBPartnerInfo (ctx, rs, null));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, "find - " + finalSQL, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
// Return
MBPartnerInfo[] retValue = new MBPartnerInfo[list.size()];
list.toArray(retValue);
return retValue;
} // find
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MBPartnerInfo.class);
/**************************************************************************
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBPartnerInfo (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBPartnerInfo
} // MBPartnerInfo

View File

@ -0,0 +1,265 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Partner Location Model
*
* @author Jorg Janke
* @version $Id: MBPartnerLocation.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MBPartnerLocation extends X_C_BPartner_Location
{
/**
* Get Locations for BPartner
* @param ctx context
* @param C_BPartner_ID bp
* @return array of locations
*/
public static MBPartnerLocation[] getForBPartner (Properties ctx, int C_BPartner_ID)
{
ArrayList<MBPartnerLocation> list = new ArrayList<MBPartnerLocation>();
String sql = "SELECT * FROM C_BPartner_Location WHERE C_BPartner_ID=?";
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 MBPartnerLocation(ctx, rs, null));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, "getForBPartner", e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MBPartnerLocation[] retValue = new MBPartnerLocation[list.size ()];
list.toArray (retValue);
return retValue;
} // getForBPartner
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MBPartnerLocation.class);
/**************************************************************************
* Default Constructor
* @param ctx context
* @param C_BPartner_Location_ID id
* @param trxName transaction
*/
public MBPartnerLocation (Properties ctx, int C_BPartner_Location_ID, String trxName)
{
super (ctx, C_BPartner_Location_ID, trxName);
if (C_BPartner_Location_ID == 0)
{
setName (".");
//
setIsShipTo (true);
setIsRemitTo (true);
setIsPayFrom (true);
setIsBillTo (true);
}
} // MBPartner_Location
/**
* BP Parent Constructor
* @param bp partner
*/
public MBPartnerLocation (MBPartner bp)
{
this (bp.getCtx(), 0, bp.get_TrxName());
setClientOrg(bp);
// may (still) be 0
set_ValueNoCheck ("C_BPartner_ID", new Integer(bp.getC_BPartner_ID()));
} // MBPartner_Location
/**
* Constructor from ResultSet row
* @param ctx context
* @param rs current row of result set to be loaded
* @param trxName transaction
*/
public MBPartnerLocation (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBPartner_Location
/** Cached Location */
private MLocation m_location = null;
/** Unique Name */
private String m_uniqueName = null;
private int m_unique = 0;
/**
* Get Loaction/Address
* @param requery requery
* @return location
*/
public MLocation getLocation (boolean requery)
{
if (m_location == null)
m_location = MLocation.get (getCtx(), getC_Location_ID(), get_TrxName());
return m_location;
} // getLoaction
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MBPartner_Location[ID=")
.append(get_ID())
.append(",C_Location_ID=").append(getC_Location_ID())
.append(",Name=").append(getName())
.append ("]");
return sb.toString ();
} // toString
/**************************************************************************
* Before Save.
* - Set Name
* @param newRecord new
* @return save
*/
protected boolean beforeSave (boolean newRecord)
{
if (getC_Location_ID() == 0)
return false;
// Set New Name
if (!newRecord)
return true;
MLocation address = getLocation(true);
m_uniqueName = getName();
if (m_uniqueName != null && m_uniqueName.equals(".")) // default
m_uniqueName = null;
m_unique = 0;
makeUnique(address);
// Check uniqueness
MBPartnerLocation[] locations = MBPartnerLocation.getForBPartner(getCtx(), getC_BPartner_ID());
boolean unique = locations.length == 0;
while (!unique)
{
unique = true;
for (int i = 0; i < locations.length; i++)
{
MBPartnerLocation location = locations[i];
if (location.getC_BPartner_Location_ID() == get_ID())
continue;
if (m_uniqueName.equals(location.getName()))
{
makeUnique(address);
unique = false;
break;
}
}
}
setName (m_uniqueName);
return true;
} // beforeSave
/**
* Make name Unique
* @param address address
*/
private void makeUnique (MLocation address)
{
// m_uniqueName = address.toString();
// return;
if (m_uniqueName == null)
m_uniqueName = "";
m_unique++;
// 0 - City
if (m_uniqueName.length() == 0)
{
String xx = address.getCity();
if (xx != null && xx.length() > 0)
m_uniqueName = xx;
m_unique = 0;
}
// 1 + Address1
if (m_unique == 1 || m_uniqueName.length() == 0)
{
String xx = address.getAddress1();
if (xx != null && xx.length() > 0)
{
if (m_uniqueName.length() > 0)
m_uniqueName += " ";
m_uniqueName += xx;
}
m_unique = 1;
}
// 2 + Address2
if (m_unique == 2 || m_uniqueName.length() == 0)
{
String xx = address.getAddress2();
if (xx != null && xx.length() > 0)
{
if (m_uniqueName.length() > 0)
m_uniqueName += " ";
m_uniqueName += xx;
}
m_unique = 2;
}
// 3 - Region
if (m_unique == 3 || m_uniqueName.length() == 0)
{
String xx = address.getRegionName(true);
{
if (m_uniqueName.length() > 0)
m_uniqueName += " ";
m_uniqueName += xx;
}
m_unique = 3;
}
// 4 - ID
if (m_unique == 4 || m_uniqueName.length() == 0)
{
int id = get_ID();
if (id == 0)
id = address.get_ID();
m_uniqueName += "#" + id;
m_unique = 4;
}
} // makeUnique
} // MBPartnerLocation

View File

@ -0,0 +1,88 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Bank Model
*
* @author Jorg Janke
* @version $Id: MBank.java,v 1.2 2006/07/30 00:51:05 jjanke Exp $
*/
public class MBank extends X_C_Bank
{
/**
* Get MBank from Cache
* @param ctx context
* @param C_Bank_ID id
* @return MBank
*/
public static MBank get (Properties ctx, int C_Bank_ID)
{
Integer key = new Integer (C_Bank_ID);
MBank retValue = (MBank)s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MBank (ctx, C_Bank_ID, null);
if (retValue.get_ID() != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MBank> s_cache =
new CCache<Integer,MBank> ("C_Bank", 3);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param C_Bank_ID bank
* @param trxName trx
*/
public MBank (Properties ctx, int C_Bank_ID, String trxName)
{
super (ctx, C_Bank_ID, trxName);
} // MBank
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MBank (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MBank
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MBank[");
sb.append (get_ID ()).append ("-").append(getName ()).append ("]");
return sb.toString ();
} // toString
} // MBank

View File

@ -0,0 +1,138 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Bank Account Model
*
* @author Jorg Janke
* @version $Id: MBankAccount.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
*/
public class MBankAccount extends X_C_BankAccount
{
/**
* Get BankAccount from Cache
* @param ctx context
* @param C_BankAccount_ID id
* @return MBankAccount
*/
public static MBankAccount get (Properties ctx, int C_BankAccount_ID)
{
Integer key = new Integer (C_BankAccount_ID);
MBankAccount retValue = (MBankAccount) s_cache.get (key);
if (retValue != null)
return retValue;
retValue = new MBankAccount (ctx, C_BankAccount_ID, null);
if (retValue.get_ID () != 0)
s_cache.put (key, retValue);
return retValue;
} // get
/** Cache */
private static CCache<Integer,MBankAccount> s_cache
= new CCache<Integer,MBankAccount>("C_BankAccount", 5);
/**
* Bank Account Model
* @param ctx context
* @param C_BankAccount_ID bank account
* @param trxName transaction
*/
public MBankAccount (Properties ctx, int C_BankAccount_ID, String trxName)
{
super (ctx, C_BankAccount_ID, trxName);
if (C_BankAccount_ID == 0)
{
setIsDefault (false);
setBankAccountType (BANKACCOUNTTYPE_Checking);
setCurrentBalance (Env.ZERO);
// setC_Currency_ID (0);
setCreditLimit (Env.ZERO);
// setC_BankAccount_ID (0);
}
} // MBankAccount
/**
* Bank Account Model
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBankAccount (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBankAccount
/**
* String representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MBankAccount[")
.append (get_ID())
.append("-").append(getAccountNo())
.append ("]");
return sb.toString ();
} // toString
/**
* Get Bank
* @return bank parent
*/
public MBank getBank()
{
return MBank.get(getCtx(), getC_Bank_ID());
} // getBank
/**
* Get Bank Name and Account No
* @return Bank/Account
*/
public String getName()
{
return getBank().getName() + " " + getAccountNo();
} // getName
/**
* After Save
* @param newRecord new record
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord & success)
return insert_Accounting("C_BankAccount_Acct", "C_AcctSchema_Default", null);
return success;
} // afterSave
/**
* Before Delete
* @return true
*/
protected boolean beforeDelete ()
{
return delete_Accounting("C_BankAccount_Acct");
} // beforeDelete
} // MBankAccount

View File

@ -0,0 +1,587 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.io.*;
import java.math.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.process.*;
import org.compiere.util.*;
/**
* Bank Statement Model
*
* @author Eldir Tomassen/Jorg Janke
* @version $Id: MBankStatement.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
*/
public class MBankStatement extends X_C_BankStatement implements DocAction
{
/**
* Standard Constructor
* @param ctx context
* @param C_BankStatement_ID id
* @param trxName transaction
*/
public MBankStatement (Properties ctx, int C_BankStatement_ID, String trxName)
{
super (ctx, C_BankStatement_ID, trxName);
if (C_BankStatement_ID == 0)
{
// setC_BankAccount_ID (0); // parent
setStatementDate (new Timestamp(System.currentTimeMillis())); // @Date@
setDocAction (DOCACTION_Complete); // CO
setDocStatus (DOCSTATUS_Drafted); // DR
setBeginningBalance(Env.ZERO);
setStatementDifference(Env.ZERO);
setEndingBalance (Env.ZERO);
setIsApproved (false); // N
setIsManual (true); // Y
setPosted (false); // N
super.setProcessed (false);
}
} // MBankStatement
/**
* Load Constructor
* @param ctx Current context
* @param rs result set
* @param trxName transaction
*/
public MBankStatement(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBankStatement
/**
* Parent Constructor
* @param account Bank Account
* @param isManual Manual statement
**/
public MBankStatement (MBankAccount account, boolean isManual)
{
this (account.getCtx(), 0, account.get_TrxName());
setClientOrg(account);
setC_BankAccount_ID(account.getC_BankAccount_ID());
setStatementDate(new Timestamp(System.currentTimeMillis()));
setBeginningBalance(account.getCurrentBalance());
setName(getStatementDate().toString());
setIsManual(isManual);
} // MBankStatement
/**
* Create a new Bank Statement
* @param account Bank Account
*/
public MBankStatement(MBankAccount account)
{
this(account, false);
} // MBankStatement
/** Lines */
private MBankStatementLine[] m_lines = null;
/**
* Get Bank Statement Lines
* @param requery requery
* @return line array
*/
public MBankStatementLine[] getLines (boolean requery)
{
if (m_lines != null && !requery)
return m_lines;
//
ArrayList<MBankStatementLine> list = new ArrayList<MBankStatementLine>();
String sql = "SELECT * FROM C_BankStatementLine "
+ "WHERE C_BankStatement_ID=?"
+ "ORDER BY Line";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, getC_BankStatement_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add (new MBankStatementLine(getCtx(), rs, get_TrxName()));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, "getLines", e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MBankStatementLine[] retValue = new MBankStatementLine[list.size()];
list.toArray(retValue);
return retValue;
} // getLines
/**
* Add to Description
* @param description text
*/
public void addDescription (String description)
{
String desc = getDescription();
if (desc == null)
setDescription(description);
else
setDescription(desc + " | " + description);
} // addDescription
/**
* Set Processed.
* Propergate to Lines/Taxes
* @param processed processed
*/
public void setProcessed (boolean processed)
{
super.setProcessed (processed);
if (get_ID() == 0)
return;
String sql = "UPDATE C_BankStatementLine SET Processed='"
+ (processed ? "Y" : "N")
+ "' WHERE C_BankStatement_ID=" + getC_BankStatement_ID();
int noLine = DB.executeUpdate(sql, get_TrxName());
m_lines = null;
log.fine("setProcessed - " + processed + " - Lines=" + noLine);
} // setProcessed
/**
* Get Bank Account
* @return bank Account
*/
public MBankAccount getBankAccount()
{
return MBankAccount.get(getCtx(), getC_BankAccount_ID());
} // getBankAccount
/**
* Get Document No
* @return name
*/
public String getDocumentNo()
{
return getName();
} // getDocumentNo
/**
* Get Document Info
* @return document info (untranslated)
*/
public String getDocumentInfo()
{
return getBankAccount().getName() + " " + getDocumentNo();
} // getDocumentInfo
/**
* Create PDF
* @return File or null
*/
public File createPDF ()
{
try
{
File temp = File.createTempFile(get_TableName()+get_ID()+"_", ".pdf");
return createPDF (temp);
}
catch (Exception e)
{
log.severe("Could not create PDF - " + e.getMessage());
}
return null;
} // getPDF
/**
* Create PDF file
* @param file output file
* @return file if success
*/
public File createPDF (File file)
{
// ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID());
// if (re == null)
return null;
// return re.getPDF(file);
} // createPDF
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (getBeginningBalance().compareTo(Env.ZERO) == 0)
{
MBankAccount ba = MBankAccount.get(getCtx(), getC_BankAccount_ID());
setBeginningBalance(ba.getCurrentBalance());
}
setEndingBalance(getBeginningBalance().add(getStatementDifference()));
return true;
} // beforeSave
/**************************************************************************
* Process document
* @param processAction document action
* @return true if performed
*/
public boolean processIt (String processAction)
{
m_processMsg = null;
DocumentEngine engine = new DocumentEngine (this, getDocStatus());
return engine.processIt (processAction, getDocAction());
} // processIt
/** Process Message */
private String m_processMsg = null;
/** Just Prepared Flag */
private boolean m_justPrepared = false;
/**
* Unlock Document.
* @return true if success
*/
public boolean unlockIt()
{
log.info("unlockIt - " + toString());
setProcessing(false);
return true;
} // unlockIt
/**
* Invalidate Document
* @return true if success
*/
public boolean invalidateIt()
{
log.info("invalidateIt - " + toString());
setDocAction(DOCACTION_Prepare);
return true;
} // invalidateIt
/**
* Prepare Document
* @return new status (In Progress or Invalid)
*/
public String prepareIt()
{
log.info(toString());
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE);
if (m_processMsg != null)
return DocAction.STATUS_Invalid;
// Std Period open?
if (!MPeriod.isOpen(getCtx(), getStatementDate(), MDocType.DOCBASETYPE_BankStatement))
{
m_processMsg = "@PeriodClosed@";
return DocAction.STATUS_Invalid;
}
MBankStatementLine[] lines = getLines(true);
if (lines.length == 0)
{
m_processMsg = "@NoLines@";
return DocAction.STATUS_Invalid;
}
// Lines
BigDecimal total = Env.ZERO;
Timestamp minDate = getStatementDate();
Timestamp maxDate = minDate;
for (int i = 0; i < lines.length; i++)
{
MBankStatementLine line = lines[i];
total = total.add(line.getStmtAmt());
if (line.getDateAcct().before(minDate))
minDate = line.getDateAcct();
if (line.getDateAcct().after(maxDate))
maxDate = line.getDateAcct();
}
setStatementDifference(total);
setEndingBalance(getBeginningBalance().add(total));
if (!MPeriod.isOpen(getCtx(), minDate, MDocType.DOCBASETYPE_BankStatement)
|| !MPeriod.isOpen(getCtx(), maxDate, MDocType.DOCBASETYPE_BankStatement))
{
m_processMsg = "@PeriodClosed@";
return DocAction.STATUS_Invalid;
}
m_justPrepared = true;
if (!DOCACTION_Complete.equals(getDocAction()))
setDocAction(DOCACTION_Complete);
return DocAction.STATUS_InProgress;
} // prepareIt
/**
* Approve Document
* @return true if success
*/
public boolean approveIt()
{
log.info("approveIt - " + toString());
setIsApproved(true);
return true;
} // approveIt
/**
* Reject Approval
* @return true if success
*/
public boolean rejectIt()
{
log.info("rejectIt - " + toString());
setIsApproved(false);
return true;
} // rejectIt
/**
* Complete Document
* @return new status (Complete, In Progress, Invalid, Waiting ..)
*/
public String completeIt()
{
// Re-Check
if (!m_justPrepared)
{
String status = prepareIt();
if (!DocAction.STATUS_InProgress.equals(status))
return status;
}
// Implicit Approval
if (!isApproved())
approveIt();
log.info("completeIt - " + toString());
// Set Payment reconciled
MBankStatementLine[] lines = getLines(false);
for (int i = 0; i < lines.length; i++)
{
MBankStatementLine line = lines[i];
if (line.getC_Payment_ID() != 0)
{
MPayment payment = new MPayment (getCtx(), line.getC_Payment_ID(), get_TrxName());
payment.setIsReconciled(true);
payment.save(get_TrxName());
}
}
// Update Bank Account
MBankAccount ba = MBankAccount.get(getCtx(), getC_BankAccount_ID());
ba.setCurrentBalance(getEndingBalance());
ba.save(get_TrxName());
// User Validation
String valid = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE);
if (valid != null)
{
m_processMsg = valid;
return DocAction.STATUS_Invalid;
}
//
setProcessed(true);
setDocAction(DOCACTION_Close);
return DocAction.STATUS_Completed;
} // completeIt
/**
* Void Document.
* @return false
*/
public boolean voidIt()
{
log.info(toString());
if (DOCSTATUS_Closed.equals(getDocStatus())
|| DOCSTATUS_Reversed.equals(getDocStatus())
|| DOCSTATUS_Voided.equals(getDocStatus()))
{
m_processMsg = "Document Closed: " + getDocStatus();
setDocAction(DOCACTION_None);
return false;
}
// Not Processed
if (DOCSTATUS_Drafted.equals(getDocStatus())
|| DOCSTATUS_Invalid.equals(getDocStatus())
|| DOCSTATUS_InProgress.equals(getDocStatus())
|| DOCSTATUS_Approved.equals(getDocStatus())
|| DOCSTATUS_NotApproved.equals(getDocStatus()) )
;
// Std Period open?
else
{
if (!MPeriod.isOpen(getCtx(), getStatementDate(), MDocType.DOCBASETYPE_BankStatement))
{
m_processMsg = "@PeriodClosed@";
return false;
}
if (MFactAcct.delete(Table_ID, getC_BankStatement_ID(), get_TrxName()) < 0)
return false; // could not delete
}
// Set lines to 0
MBankStatementLine[] lines = getLines(true);
for (int i = 0; i < lines.length; i++)
{
MBankStatementLine line = lines[i];
BigDecimal old = line.getStmtAmt();
if (line.getStmtAmt().compareTo(Env.ZERO) != 0)
{
String description = Msg.getMsg(getCtx(), "Voided") + " ("
+ Msg.translate(getCtx(), "StmtAmt") + "=" + line.getStmtAmt();
if (line.getTrxAmt().compareTo(Env.ZERO) != 0)
description += ", " + Msg.translate(getCtx(), "TrxAmt") + "=" + line.getTrxAmt();
if (line.getChargeAmt().compareTo(Env.ZERO) != 0)
description += ", " + Msg.translate(getCtx(), "ChargeAmt") + "=" + line.getChargeAmt();
if (line.getInterestAmt().compareTo(Env.ZERO) != 0)
description += ", " + Msg.translate(getCtx(), "InterestAmt") + "=" + line.getInterestAmt();
description += ")";
line.addDescription(description);
//
line.setStmtAmt(Env.ZERO);
line.setTrxAmt(Env.ZERO);
line.setChargeAmt(Env.ZERO);
line.setInterestAmt(Env.ZERO);
line.save(get_TrxName());
//
if (line.getC_Payment_ID() != 0)
{
MPayment payment = new MPayment (getCtx(), line.getC_Payment_ID(), get_TrxName());
payment.setIsReconciled(false);
payment.save(get_TrxName());
}
}
}
addDescription(Msg.getMsg(getCtx(), "Voided"));
setStatementDifference(Env.ZERO);
setProcessed(true);
setDocAction(DOCACTION_None);
return true;
} // voidIt
/**
* Close Document.
* @return true if success
*/
public boolean closeIt()
{
log.info("closeIt - " + toString());
setDocAction(DOCACTION_None);
return true;
} // closeIt
/**
* Reverse Correction
* @return false
*/
public boolean reverseCorrectIt()
{
log.info("reverseCorrectIt - " + toString());
return false;
} // reverseCorrectionIt
/**
* Reverse Accrual
* @return false
*/
public boolean reverseAccrualIt()
{
log.info("reverseAccrualIt - " + toString());
return false;
} // reverseAccrualIt
/**
* Re-activate
* @return false
*/
public boolean reActivateIt()
{
log.info("reActivateIt - " + toString());
return false;
} // reActivateIt
/*************************************************************************
* Get Summary
* @return Summary of Document
*/
public String getSummary()
{
StringBuffer sb = new StringBuffer();
sb.append(getName());
// : Total Lines = 123.00 (#1)
sb.append(": ")
.append(Msg.translate(getCtx(),"StatementDifference")).append("=").append(getStatementDifference())
.append(" (#").append(getLines(false).length).append(")");
// - Description
if (getDescription() != null && getDescription().length() > 0)
sb.append(" - ").append(getDescription());
return sb.toString();
} // getSummary
/**
* Get Process Message
* @return clear text error message
*/
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
* @return AD_User_ID
*/
public int getDoc_User_ID()
{
return getUpdatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount.
* Statement Difference
* @return amount
*/
public BigDecimal getApprovalAmt()
{
return getStatementDifference();
} // getApprovalAmt
/**
* Get Document Currency
* @return C_Currency_ID
*/
public int getC_Currency_ID()
{
// MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID());
// return pl.getC_Currency_ID();
return 0;
} // getC_Currency_ID
} // MBankStatement

View File

@ -0,0 +1,218 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.*;
import java.sql.*;
import java.util.*;
import org.compiere.util.*;
/**
* Bank Statement Line Model
*
* @author Eldir Tomassen/Jorg Janke
* @version $Id: MBankStatementLine.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MBankStatementLine extends X_C_BankStatementLine
{
/**
* Standard Constructor
* @param ctx context
* @param C_BankStatementLine_ID id
* @param trxName transaction
*/
public MBankStatementLine (Properties ctx, int C_BankStatementLine_ID, String trxName)
{
super (ctx, C_BankStatementLine_ID, trxName);
if (C_BankStatementLine_ID == 0)
{
// setC_BankStatement_ID (0); // Parent
// setC_Charge_ID (0);
// setC_Currency_ID (0); // Bank Acct Currency
// setLine (0); // @SQL=SELECT NVL(MAX(Line),0)+10 AS DefaultValue FROM C_BankStatementLine WHERE C_BankStatement_ID=@C_BankStatement_ID@
setStmtAmt(Env.ZERO);
setTrxAmt(Env.ZERO);
setInterestAmt(Env.ZERO);
setChargeAmt(Env.ZERO);
setIsReversal (false);
// setValutaDate (new Timestamp(System.currentTimeMillis())); // @StatementDate@
// setDateAcct (new Timestamp(System.currentTimeMillis())); // @StatementDate@
}
} // MBankStatementLine
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBankStatementLine (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBankStatementLine
/**
* Parent Constructor
* @param statement Bank Statement that the line is part of
*/
public MBankStatementLine(MBankStatement statement)
{
this (statement.getCtx(), 0, statement.get_TrxName());
setClientOrg(statement);
setC_BankStatement_ID(statement.getC_BankStatement_ID());
setStatementLineDate(statement.getStatementDate());
} // MBankStatementLine
/**
* Parent Constructor
* @param statement Bank Statement that the line is part of
* @param lineNo position of the line within the statement
*/
public MBankStatementLine(MBankStatement statement, int lineNo)
{
this (statement);
setLine(lineNo);
} // MBankStatementLine
/**
* Set Statement Line Date and all other dates (Valuta, Acct)
* @param StatementLineDate date
*/
public void setStatementLineDate(Timestamp StatementLineDate)
{
super.setStatementLineDate(StatementLineDate);
setValutaDate (StatementLineDate);
setDateAcct (StatementLineDate);
} // setStatementLineDate
/**
* Set Payment
* @param payment payment
*/
public void setPayment (MPayment payment)
{
setC_Payment_ID (payment.getC_Payment_ID());
setC_Currency_ID (payment.getC_Currency_ID());
//
BigDecimal amt = payment.getPayAmt(true);
setTrxAmt(amt);
setStmtAmt(amt);
//
setDescription(payment.getDescription());
} // setPayment
/**
* Add to Description
* @param description text
*/
public void addDescription (String description)
{
String desc = getDescription();
if (desc == null)
setDescription(description);
else
setDescription(desc + " | " + description);
} // addDescription
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (getChargeAmt().signum() != 0 && getC_Charge_ID() == 0)
{
log.saveError("FillMandatory", Msg.getElement(getCtx(), "C_Charge_ID"));
return false;
}
// Set Line No
if (getLine() == 0)
{
String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_BankStatementLine WHERE C_BankStatement_ID=?";
int ii = DB.getSQLValue (get_TrxName(), sql, getC_BankStatement_ID());
setLine (ii);
}
// Set References
if (getC_Payment_ID() != 0 && getC_BPartner_ID() == 0)
{
MPayment payment = new MPayment (getCtx(), getC_Payment_ID(), get_TrxName());
setC_BPartner_ID(payment.getC_BPartner_ID());
if (payment.getC_Invoice_ID() != 0)
setC_Invoice_ID(payment.getC_Invoice_ID());
}
if (getC_Invoice_ID() != 0 && getC_BPartner_ID() == 0)
{
MInvoice invoice = new MInvoice (getCtx(), getC_Invoice_ID(), get_TrxName());
setC_BPartner_ID(invoice.getC_BPartner_ID());
}
// Calculate Charge = Statement - trx - Interest
BigDecimal amt = getStmtAmt();
amt = amt.subtract(getTrxAmt());
amt = amt.subtract(getInterestAmt());
if (amt.compareTo(getChargeAmt()) != 0)
setChargeAmt (amt);
//
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
updateHeader();
return success;
} // afterSave
/**
* After Delete
* @param success success
* @return success
*/
protected boolean afterDelete (boolean success)
{
updateHeader();
return success;
} // afterSave
/**
* Update Header
*/
private void updateHeader()
{
String sql = "UPDATE C_BankStatement bs"
+ " SET StatementDifference=(SELECT SUM(StmtAmt) FROM C_BankStatementLine bsl "
+ "WHERE bsl.C_BankStatement_ID=bs.C_BankStatement_ID AND bsl.IsActive='Y') "
+ "WHERE C_BankStatement_ID=" + getC_BankStatement_ID();
DB.executeUpdate(sql, get_TrxName());
sql = "UPDATE C_BankStatement bs"
+ " SET EndingBalance=BeginningBalance+StatementDifference "
+ "WHERE C_BankStatement_ID=" + getC_BankStatement_ID();
DB.executeUpdate(sql, get_TrxName());
} // updateHeader
} // MBankStatementLine

View File

@ -0,0 +1,300 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import org.compiere.impexp.*;
/**
* Bank Statement Loader Model
* This class is responsible for creating an instance of the
* bank statement loader class to use.
* It also inserts the data into the I_BankStatement table.
*
* The loader objects can acces their configuration (e.g. file, URL,
* password etc) using the corresponding get methods provided by this class.
* As this class is derrived from PO, "Persistent Object" it has acces to
* the loader configuration that has been entered for this loader.
* How these values are interpreted is the responsibility of the loader.
* There are two file names provided, getFileName() and getLocalFileName().
* The first one is the file name as entered on the loader configuration tab,
* the second one is the file name parameter from the loader process.
* Reccomended behaviour for a file based loader would be to use the file
* name from the process parameter if available, and resort to the file anme
* from the loader configuration as a second option.
*
* For a HTTP based loader the file name from the loader configuration should
* be used to construct the URL to connect to (combined with the other parameters).
* In this scenario the file name from the process parameter can be used to save
* the aquired statement data to disk.
*
* author Maarten Klinker, Eldir Tomassen
* @version $Id: MBankStatementLoader.java,v 1.3 2006/07/30 00:51:04 jjanke Exp $
*/
public class MBankStatementLoader extends X_C_BankStatementLoader
{
/** Number of statement lines imported */
private int loadCount = 0;
/** Message will be handled by Adempiere (e.g. translated) */
private String errorMessage = "";
/** Additional error description */
private String errorDescription = "";
/** Loader object to use */
private BankStatementLoaderInterface m_loader = null;
/** File name from process parameter */
private String localFileName = null;
/**
* Create a Statement Loader
* Added for compatibility with new PO infrastructure (bug# 968136)
* @param ctx Current context
* @param C_BankStatementLoader_ID loader to use
* @param trxName transaction
*/
public MBankStatementLoader(Properties ctx, int C_BankStatementLoader_ID, String trxName)
{
super(ctx, C_BankStatementLoader_ID, trxName);
init(null);
} // MBankStatementLoader
/**
* Create a Statement Loader
* @param ctx Current context
* @param C_BankStatementLoader_ID loader to use
* @param fileName input file
* @param trxName transaction
*/
public MBankStatementLoader(Properties ctx, int C_BankStatementLoader_ID, String fileName, String trxName)
{
super(ctx, C_BankStatementLoader_ID, trxName);
init(fileName);
} // MBankStatementLoader
/**
* Create a Statement Loader
* @param ctx Current context
* @param rs ResultSet
* @param trxName transaction
*/
public MBankStatementLoader(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
init(null);
} // MBankStatementLoader
private void init(String fileName)
{
localFileName = fileName;
try
{
log.info( "MBankStatementLoader Class Name=" + getStmtLoaderClass());
Class bsrClass = Class.forName(getStmtLoaderClass());
m_loader = (BankStatementLoaderInterface) bsrClass.newInstance();
}
catch(Exception e)
{
errorMessage = "ClassNotLoaded";
errorDescription = e.getMessage();
}
}
/**
* Return Name
* @return Name
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MBankStatementLoader[")
.append(get_ID ()).append("-").append(getName())
.append ("]");
return sb.toString ();
} // toString
/**
* Return Local File Name
* @return Name
*/
public String getLocalFileName()
{
return localFileName;
} // getLocalFileName
/**
* Start loading Bankstatements
* @return true if loading completed succesfully
*/
public boolean loadLines()
{
boolean result = false;
log.info( "MBankStatementLoader.loadLines");
if (m_loader == null)
{
errorMessage = "ClassNotLoaded";
return result;
}
// Initialize the Loader
if (!m_loader.init(this))
{
errorMessage = m_loader.getLastErrorMessage();
errorDescription = m_loader.getLastErrorDescription();
return result;
}
// Verify whether the data structure is valid
if (!m_loader.isValid())
{
errorMessage = m_loader.getLastErrorMessage();
errorDescription = m_loader.getLastErrorDescription();
return result;
}
// Load statement lines
if (!m_loader.loadLines())
{
errorMessage = m_loader.getLastErrorMessage();
errorDescription = m_loader.getLastErrorDescription();
return result;
}
result = true;
return result;
} // loadLines
/**
* Load a bank statement into the I_BankStatement table
* @return Statement line was loaded succesfully
* This method is called by the BankStatementLoadere whenever a complete
* statement line has been read.
*/
public boolean saveLine()
{
log.info( "MBankStatementLoader.importLine");
boolean result = false;
X_I_BankStatement imp = new X_I_BankStatement(getCtx(), 0, get_TrxName());
if (m_loader == null)
{
errorMessage = "LoadError";
return result;
}
// Bank Account fields
log.config( "MBankStatementLoader.importLine Bank Account=" + m_loader.getBankAccountNo());
imp.setBankAccountNo(m_loader.getBankAccountNo());
log.config( "MBankStatementLoader.importLine Routing No=" + m_loader.getRoutingNo());
imp.setRoutingNo(m_loader.getRoutingNo());
// Statement fields
log.config( "MBankStatementLoader.importLine EFT Statement Reference No=" + m_loader.getStatementReference());
imp.setEftStatementReference(m_loader.getStatementReference());
log.config( "MBankStatementLoader.importLine EFT Statement Date=" + m_loader.getStatementDate());
imp.setEftStatementDate(m_loader.getStatementDate());
log.config( "MBankStatementLoader.importLine Statement Date=" + m_loader.getStatementDate());
imp.setStatementDate(m_loader.getStatementDate());
// Statement Line fields
log.config( "MBankStatementLoader.importLine EFT Transaction ID=" + m_loader.getTrxID());
imp.setEftTrxID(m_loader.getTrxID());
log.config( "MBankStatementLoader.importLine Statement Line Date=" + m_loader.getStatementLineDate());
imp.setStatementLineDate(m_loader.getStatementLineDate());
imp.setStatementLineDate(m_loader.getStatementLineDate());
imp.setEftStatementLineDate(m_loader.getStatementLineDate());
log.config( "MBankStatementLoader.importLine Valuta Date=" + m_loader.getValutaDate());
imp.setValutaDate(m_loader.getValutaDate());
imp.setEftValutaDate(m_loader.getValutaDate());
log.config( "MBankStatementLoader.importLine Statement Amount=" + m_loader.getStmtAmt());
imp.setStmtAmt(m_loader.getStmtAmt());
imp.setEftAmt(m_loader.getStmtAmt());
log.config( "MBankStatementLoader.importLine Transaction Amount=" + m_loader.getTrxAmt());
imp.setTrxAmt(m_loader.getTrxAmt());
log.config( "MBankStatementLoader.importLine Interest Amount=" + m_loader.getInterestAmt());
imp.setInterestAmt(m_loader.getInterestAmt());
log.config( "MBankStatementLoader.importLine Reference No=" + m_loader.getReference());
imp.setReferenceNo(m_loader.getReference());
imp.setEftReference(m_loader.getReference());
log.config( "MBankStatementLoader.importLine Check No=" + m_loader.getReference());
imp.setEftCheckNo(m_loader.getCheckNo());
log.config( "MBankStatementLoader.importLine Memo=" + m_loader.getMemo());
imp.setMemo(m_loader.getMemo());
imp.setEftMemo(m_loader.getMemo());
log.config( "MBankStatementLoader.importLine Payee Name=" + m_loader.getPayeeName());
imp.setEftPayee(m_loader.getPayeeName());
log.config( "MBankStatementLoader.importLine Payee Account No=" + m_loader.getPayeeAccountNo());
imp.setEftPayeeAccount(m_loader.getPayeeAccountNo());
log.config( "MBankStatementLoader.importLine EFT Transaction Type=" + m_loader.getTrxType());
imp.setEftTrxType(m_loader.getTrxType());
log.config( "MBankStatementLoader.importLine Currency=" + m_loader.getCurrency());
imp.setEftCurrency(m_loader.getCurrency());
imp.setISO_Code(m_loader.getCurrency());
log.config( "MBankStatementLoader.importLine Charge Name=" + m_loader.getChargeName());
imp.setChargeName(m_loader.getChargeName());
log.config( "MBankStatementLoader.importLine Charge Amount=" + m_loader.getChargeAmt());
imp.setChargeAmt(m_loader.getChargeAmt());
imp.setProcessed(false);
imp.setI_IsImported(false);
result = imp.save();
if (result)
{
loadCount ++;
}
else
{
errorMessage = "LoadError";
}
imp = null;
return result;
} // importLine
/**
* Return the most recent error
* @return Error message
* This error message will be handled as a Adempiere message,
* (e.g. it can be translated)
*/
public String getErrorMessage()
{
return errorMessage;
} // getErrorMessage
/**
* Return the most recent error description
* @return Error discription
* This is an additional error description, it can be used to provided
* descriptive iformation, such as a file name or SQL error, that can not
* be translated by the Adempiere message system.
*/
public String getErrorDescription()
{
return errorDescription;
} // getErrorDescription
/**
* The total number of statement lines loaded
* @return Number of imported statement lines
*/
public int getLoadCount()
{
return loadCount;
} // getLoadCount
} //MBankStatementLoader

View File

@ -0,0 +1,146 @@
/******************************************************************************
* 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. *
* 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 *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.impexp.*;
import org.compiere.util.*;
/**
* Bank Statement Matcher Algorithm
*
* @author Jorg Janke
* @version $Id: MBankStatementMatcher.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MBankStatementMatcher extends X_C_BankStatementMatcher
{
/**
* Get Bank Statement Matcher Algorithms
* @param ctx context
* @param trxName transaction
* @return matchers
*/
public static MBankStatementMatcher[] getMatchers (Properties ctx, String trxName)
{
ArrayList<MBankStatementMatcher> list = new ArrayList<MBankStatementMatcher>();
String sql = MRole.getDefault(ctx, false).addAccessSQL(
"SELECT * FROM C_BankStatementMatcher ORDER BY SeqNo",
"C_BankStatementMatcher", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
int AD_Client_ID = Env.getAD_Client_ID(ctx);
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
list.add (new MBankStatementMatcher(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;
}
// Convert
MBankStatementMatcher[] retValue = new MBankStatementMatcher[list.size()];
list.toArray(retValue);
return retValue;
} // getMatchers
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger(MBankStatementMatcher.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param C_BankStatementMatcher_ID id
* @param trxName transaction
*/
public MBankStatementMatcher(Properties ctx, int C_BankStatementMatcher_ID, String trxName)
{
super(ctx, C_BankStatementMatcher_ID, trxName);
} // MBankStatementMatcher
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MBankStatementMatcher(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MBankStatementMatcher
private BankStatementMatcherInterface m_matcher = null;
private Boolean m_matcherValid = null;
/**
* Is Matcher Valid
* @return true if valid
*/
public boolean isMatcherValid()
{
if (m_matcherValid == null)
getMatcher();
return m_matcherValid.booleanValue();
} // isMatcherValid
/**
* Get Matcher
* @return Matcher Instance
*/
public BankStatementMatcherInterface getMatcher()
{
if (m_matcher != null
|| (m_matcherValid != null && m_matcherValid.booleanValue()))
return m_matcher;
String className = getClassname();
if (className == null || className.length() == 0)
return null;
try
{
Class matcherClass = Class.forName(className);
m_matcher = (BankStatementMatcherInterface)matcherClass.newInstance();
m_matcherValid = Boolean.TRUE;
}
catch (Exception e)
{
log.log(Level.SEVERE, className, e);
m_matcher = null;
m_matcherValid = Boolean.FALSE;
}
return m_matcher;
} // getMatcher
} // MBankStatementMatcher

Some files were not shown because too many files have changed in this diff Show More