FR [ 2520591 ] Support multiples calendar for Org
+ * @see http://sourceforge.net/tracker2/?func=detail&atid=879335&aid=2520591&group_id=176962
* @version $Id: Doc.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $
*/
public abstract class Doc
{
- /** AD_Table_ID's of documents */
- private static int[] documentsTableID = null;
-
- /** Table Names of documents */
- private static String[] documentsTableName = null;
-
/**************************************************************************
* Document Types
* --------------
@@ -175,7 +167,7 @@ public abstract class Doc
/** Purchase Requisition */
public static final String DOCTYPE_PurchaseRequisition = "POR";
-
+
// Posting Status - AD_Reference_ID=234 //
/** Document Status */
public static final String STATUS_NotPosted = "N";
@@ -194,144 +186,32 @@ public abstract class Doc
/** Document Status */
public static final String STATUS_Error = "E";
-
+
/**
* Create Posting document
- * @param ass accounting schema
+ * @param as accounting schema
* @param AD_Table_ID Table ID of Documents
* @param Record_ID record ID to load
* @param trxName transaction name
* @return Document or null
*/
- public static Doc get (MAcctSchema[] ass, int AD_Table_ID, int Record_ID, String trxName)
+ public static Doc get (MAcctSchema as, int AD_Table_ID, int Record_ID, String trxName)
{
- String TableName = null;
- for (int i = 0; i < getDocumentsTableID().length; i++)
- {
- if (getDocumentsTableID()[i] == AD_Table_ID)
- {
- TableName = getDocumentsTableName()[i];
- break;
- }
- }
- if (TableName == null)
- {
- s_log.severe("Not found AD_Table_ID=" + AD_Table_ID);
- return null;
- }
- //
- Doc doc = null;
- StringBuffer sql = new StringBuffer("SELECT * FROM ")
- .append(TableName)
- .append(" WHERE ").append(TableName).append("_ID=? AND Processed='Y'");
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try
- {
- pstmt = DB.prepareStatement (sql.toString(), trxName);
- pstmt.setInt (1, Record_ID);
- rs = pstmt.executeQuery ();
- if (rs.next ())
- {
- doc = get (ass, AD_Table_ID, rs, trxName);
- }
- else
- s_log.severe("Not Found: " + TableName + "_ID=" + Record_ID);
- }
- catch (Exception e)
- {
- s_log.log (Level.SEVERE, sql.toString(), e);
- }
- finally
- {
- DB.close(rs, pstmt);
- rs = null;
- pstmt = null;
- }
- return doc;
+ return DocManager.getDocument(as, AD_Table_ID, Record_ID, trxName);
} // get
-
+
/**
* Create Posting document
- * @param ass accounting schema
+ * @param as accounting schema
* @param AD_Table_ID Table ID of Documents
* @param rs ResultSet
* @param trxName transaction name
* @return Document
- * @throws AdempiereUserError
+ * @throws AdempiereUserError
*/
- public static Doc get (MAcctSchema[] ass, int AD_Table_ID, ResultSet rs, String trxName) throws AdempiereUserError
+ public static Doc get (MAcctSchema as, int AD_Table_ID, ResultSet rs, String trxName)
{
- Doc doc = null;
-
- /* Classname of the Doc class follows this convention:
- * if the prefix (letters before the first underscore _) is 1 character, then the class is Doc_TableWithoutPrefixWithoutUnderscores
- * otherwise Doc_WholeTableWithoutUnderscores
- * i.e. following this query
- SELECT t.ad_table_id, tablename,
- CASE
- WHEN instr(tablename, '_') = 2
- THEN 'Doc_' || substr(tablename, 3)
- WHEN instr(tablename, '_') > 2
- THEN 'Doc_' ||
- ELSE ''
- REPLACE
- (
- tablename, '_', ''
- )
- END AS classname
- FROM ad_table t, ad_column C
- WHERE t.ad_table_id = C.ad_table_id AND
- C.columnname = 'Posted' AND
- isview = 'N'
- ORDER BY 1
- * This is:
- * 224 GL_Journal Doc_GLJournal
- * 259 C_Order Doc_Order
- * 318 C_Invoice Doc_Invoice
- * 319 M_InOut Doc_InOut
- * 321 M_Inventory Doc_Inventory
- * 323 M_Movement Doc_Movement
- * 325 M_Production Doc_Production
- * 335 C_Payment Doc_Payment
- * 392 C_BankStatement Doc_BankStatement
- * 407 C_Cash Doc_Cash
- * 472 M_MatchInv Doc_MatchInv
- * 473 M_MatchPO Doc_MatchPO
- * 623 C_ProjectIssue Doc_ProjectIssue
- * 702 M_Requisition Doc_Requisition
- * 735 C_AllocationHdr Doc_AllocationHdr
- * 53027 PP_Order Doc_PPOrder
- * 53035 PP_Cost_Collector Doc_PPCostCollector
- * 53037 DD_Order Doc_DDOrder
- * 53092 HR_Process Doc_HRProcess
- */
-
- String tableName = MTable.getTableName(Env.getCtx(), AD_Table_ID);
- String packageName = "org.compiere.acct";
- String className = null;
-
- int firstUnderscore = tableName.indexOf("_");
- if (firstUnderscore == 1)
- className = packageName + ".Doc_" + tableName.substring(2).replaceAll("_", "");
- else
- className = packageName + ".Doc_" + tableName.replaceAll("_", "");
-
- try
- {
- Class> cClass = Class.forName(className);
- Constructor> cnstr = cClass.getConstructor(new Class[] {MAcctSchema[].class, ResultSet.class, String.class});
- doc = (Doc) cnstr.newInstance(ass, rs, trxName);
- }
- catch (Exception e)
- {
- s_log.log(Level.SEVERE, "Doc Class invalid: " + className + " (" + e.toString() + ")");
- throw new AdempiereUserError("Doc Class invalid: " + className + " (" + e.toString() + ")");
- }
-
- if (doc == null)
- s_log.log(Level.SEVERE, "Unknown AD_Table_ID=" + AD_Table_ID);
- return doc;
+ return DocManager.getDocument(as, AD_Table_ID, rs, trxName);
} // get
/**
@@ -343,13 +223,10 @@ public abstract class Doc
* @param trxName transaction
* @return null if the document was posted or error message
*/
- public static String postImmediate (MAcctSchema[] ass,
+ public static String postImmediate (MAcctSchema[] ass,
int AD_Table_ID, int Record_ID, boolean force, String trxName)
{
- Doc doc = get (ass, AD_Table_ID, Record_ID, trxName);
- if (doc != null)
- return doc.post (force, true); // repost
- return "NoDoc";
+ return DocManager.postDocument(ass, AD_Table_ID, Record_ID, force, true, trxName);
} // post
/** Static Log */
@@ -357,25 +234,25 @@ public abstract class Doc
/** Log per Document */
protected CLogger log = CLogger.getCLogger(getClass());
- /* If the transaction must be managed locally (false if it's managed externally by the caller) */
+ /* If the transaction must be managed locally (false if it's managed externally by the caller) */
private boolean m_manageLocalTrx;
-
+
/**************************************************************************
* Constructor
- * @param ass accounting schemata
+ * @param as accounting schema
* @param clazz Document Class
* @param rs result set
* @param defaultDocumentType default document type or null
* @param trxName trx
*/
- Doc (MAcctSchema[] ass, Class> clazz, ResultSet rs, String defaultDocumentType, String trxName)
+ Doc (MAcctSchema as, Class> clazz, ResultSet rs, String defaultDocumentType, String trxName)
{
p_Status = STATUS_Error;
- m_ass = ass;
- m_ctx = new Properties(m_ass[0].getCtx());
- m_ctx.setProperty("#AD_Client_ID", String.valueOf(m_ass[0].getAD_Client_ID()));
-
+ m_as = as;
+ m_ctx = new Properties(m_as.getCtx());
+ m_ctx.setProperty("#AD_Client_ID", String.valueOf(m_as.getAD_Client_ID()));
+
String className = clazz.getName();
className = className.substring(className.lastIndexOf('.')+1);
try
@@ -389,31 +266,32 @@ public abstract class Doc
log.severe(msg);
throw new IllegalArgumentException(msg);
}
-
+
// DocStatus
int index = p_po.get_ColumnIndex("DocStatus");
if (index != -1)
m_DocStatus = (String)p_po.get_Value(index);
-
+
// Document Type
setDocumentType (defaultDocumentType);
m_trxName = trxName;
m_manageLocalTrx = false;
- if (m_trxName == null) {
+ if (m_trxName == null)
+ {
m_trxName = "Post" + m_DocumentType + p_po.get_ID();
m_manageLocalTrx = true;
}
p_po.set_TrxName(m_trxName);
// Amounts
- m_Amounts[0] = Env.ZERO;
- m_Amounts[1] = Env.ZERO;
- m_Amounts[2] = Env.ZERO;
- m_Amounts[3] = Env.ZERO;
+ for(int i = 0; i < m_Amounts.length; i++)
+ {
+ m_Amounts[i] = Env.ZERO;
+ }
} // Doc
- /** Accounting Schema Array */
- private MAcctSchema[] m_ass = null;
+ /** Accounting Schema */
+ private MAcctSchema m_as = null;
/** Properties */
private Properties m_ctx = null;
/** Transaction Name */
@@ -467,7 +345,7 @@ public abstract class Doc
/** No Currency in Document Indicator (-1) */
protected static final int NO_CURRENCY = -2;
-
+
/** Actual Document Status */
protected String p_Status = null;
public String getPostStatus() {
@@ -476,8 +354,8 @@ public abstract class Doc
/** Error Message */
protected String p_Error = null;
-
-
+
+
/**
* Get Context
* @return context
@@ -495,7 +373,7 @@ public abstract class Doc
{
return p_po.get_TableName();
} // get_TableName
-
+
/**
* Get Table ID
* @return table id
@@ -513,16 +391,16 @@ public abstract class Doc
{
return p_po.get_ID();
} // get_ID
-
+
/**
* Get Persistent Object
* @return po
*/
- protected PO getPO()
+ public PO getPO()
{
return p_po;
} // getPO
-
+
/**
* Post Document.
*
@@ -550,14 +428,14 @@ public abstract class Doc
else
return "Invalid DocStatus='" + m_DocStatus + "' for DocumentNo=" + getDocumentNo();
//
- if (p_po.getAD_Client_ID() != m_ass[0].getAD_Client_ID())
+ if (p_po.getAD_Client_ID() != m_as.getAD_Client_ID())
{
String error = "AD_Client_ID Conflict - Document=" + p_po.getAD_Client_ID()
- + ", AcctSchema=" + m_ass[0].getAD_Client_ID();
+ + ", AcctSchema=" + m_as.getAD_Client_ID();
log.severe(error);
return error;
}
-
+
// Lock Record ----
String trxName = null; // outside trx if on server
if (! m_manageLocalTrx)
@@ -574,13 +452,13 @@ public abstract class Doc
log.info("Locked: " + get_TableName() + "_ID=" + get_ID());
else
{
- log.log(Level.SEVERE, "Resubmit - Cannot lock " + get_TableName() + "_ID="
+ log.log(Level.SEVERE, "Resubmit - Cannot lock " + get_TableName() + "_ID="
+ get_ID() + ", Force=" + force + ",RePost=" + repost);
if (force)
return "Cannot Lock - ReSubmit";
return "Cannot Lock - ReSubmit or RePost with Force";
}
-
+
p_Error = loadDocumentDetails();
if (p_Error != null)
return p_Error;
@@ -606,43 +484,36 @@ public abstract class Doc
trx.commit(); trx.close();
return "AlreadyPosted";
}
-
+
p_Status = STATUS_NotPosted;
// Create Fact per AcctSchema
m_fact = new ArrayList();
- // for all Accounting Schema
- boolean OK = true;
getPO().setDoc(this);
try
{
- for (int i = 0; OK && i < m_ass.length; i++)
+ // if acct schema has "only" org, skip
+ boolean skip = false;
+ if (m_as.getAD_OrgOnly_ID() != 0)
{
- // if acct schema has "only" org, skip
- boolean skip = false;
- if (m_ass[i].getAD_OrgOnly_ID() != 0)
+ // Header Level Org
+ skip = m_as.isSkipOrg(getAD_Org_ID());
+ // Line Level Org
+ if (p_lines != null)
{
- // Header Level Org
- skip = m_ass[i].isSkipOrg(getAD_Org_ID());
- // Line Level Org
- if (p_lines != null)
+ for (int line = 0; skip && line < p_lines.length; line++)
{
- for (int line = 0; skip && line < p_lines.length; line++)
- {
- skip = m_ass[i].isSkipOrg(p_lines[line].getAD_Org_ID());
- if (!skip)
- break;
- }
+ skip = m_as.isSkipOrg(p_lines[line].getAD_Org_ID());
+ if (!skip)
+ break;
}
}
- if (skip)
- continue;
+ }
+ if (!skip)
+ {
// post
- log.info("(" + i + ") " + p_po);
- p_Status = postLogic (i);
- if (!p_Status.equals(STATUS_Posted))
- OK = false;
+ p_Status = postLogic ();
}
}
catch (Exception e)
@@ -650,39 +521,36 @@ public abstract class Doc
log.log(Level.SEVERE, "", e);
p_Status = STATUS_Error;
p_Error = e.toString();
- OK = false;
}
String validatorMsg = null;
// Call validator on before post
- if (p_Status.equals(STATUS_Posted)) {
+ if (!p_Status.equals(STATUS_Error)) {
validatorMsg = ModelValidationEngine.get().fireDocValidate(getPO(), ModelValidator.TIMING_BEFORE_POST);
if (validatorMsg != null) {
p_Status = STATUS_Error;
p_Error = validatorMsg;
- OK = false;
}
}
// commitFact
p_Status = postCommit (p_Status);
- if (p_Status.equals(STATUS_Posted)) {
+ if (!p_Status.equals(STATUS_Error)) {
validatorMsg = ModelValidationEngine.get().fireDocValidate(getPO(), ModelValidator.TIMING_AFTER_POST);
if (validatorMsg != null) {
p_Status = STATUS_Error;
p_Error = validatorMsg;
- OK = false;
}
}
-
+
// Create Note
if (!p_Status.equals(STATUS_Posted))
{
// Insert Note
String AD_MessageValue = "PostingError-" + p_Status;
int AD_User_ID = p_po.getUpdatedBy();
- MNote note = new MNote (getCtx(), AD_MessageValue, AD_User_ID,
+ MNote note = new MNote (getCtx(), AD_MessageValue, AD_User_ID,
getAD_Client_ID(), getAD_Org_ID(), null);
note.setRecord(p_po.get_Table_ID(), p_po.get_ID());
// Reference
@@ -699,7 +567,8 @@ public abstract class Doc
.append(", Amount=").append(getAmount())
.append(", Sta=").append(p_Status)
.append(" - PeriodOpen=").append(isPeriodOpen())
- .append(", Balanced=").append(isBalanced());
+ .append(", Balanced=").append(isBalanced())
+ .append(", Schema=").append(m_as.getName());
note.setTextMsg(Text.toString());
note.save();
p_Error = Text.toString();
@@ -723,11 +592,12 @@ public abstract class Doc
* Delete Accounting
* @return number of records
*/
- private int deleteAcct()
+ protected int deleteAcct()
{
StringBuffer sql = new StringBuffer ("DELETE Fact_Acct WHERE AD_Table_ID=")
.append(get_Table_ID())
- .append(" AND Record_ID=").append(p_po.get_ID());
+ .append(" AND Record_ID=").append(p_po.get_ID())
+ .append(" AND C_AcctSchema_ID=").append(m_as.getC_AcctSchema_ID());
int no = DB.executeUpdate(sql.toString(), getTrxName());
if (no != 0)
log.info("deleted=" + no);
@@ -736,19 +606,16 @@ public abstract class Doc
/**
* Posting logic for Accounting Schema index
- * @param index Accounting Schema index
* @return posting status/error code
*/
- private final String postLogic (int index)
+ private final String postLogic ()
{
- log.info("(" + index + ") " + p_po);
-
// rejectUnbalanced
- if (!m_ass[index].isSuspenseBalancing() && !isBalanced())
+ if (!m_as.isSuspenseBalancing() && !isBalanced())
return STATUS_NotBalanced;
// rejectUnconvertible
- if (!isConvertible(m_ass[index]))
+ if (!isConvertible(m_as))
return STATUS_NotConvertible;
// rejectPeriodClosed
@@ -756,17 +623,17 @@ public abstract class Doc
return STATUS_PeriodClosed;
// createFacts
- ArrayList facts = createFacts (m_ass[index]);
+ ArrayList facts = createFacts (m_as);
if (facts == null)
return STATUS_Error;
-
+
// call modelValidator
- String validatorMsg = ModelValidationEngine.get().fireFactsValidate(m_ass[index], facts, getPO());
+ String validatorMsg = ModelValidationEngine.get().fireFactsValidate(m_as, facts, getPO());
if (validatorMsg != null) {
p_Error = validatorMsg;
return STATUS_Error;
}
-
+
for (int f = 0; f < facts.size(); f++)
{
Fact fact = facts.get(f);
@@ -779,11 +646,11 @@ public abstract class Doc
// check accounts
if (!fact.checkAccounts())
return STATUS_InvalidAccount;
-
+
// distribute
if (!fact.distribute())
return STATUS_Error;
-
+
// balanceSource
if (!fact.isSourceBalanced())
{
@@ -807,9 +674,9 @@ public abstract class Doc
if (!fact.isAcctBalanced())
return STATUS_NotBalanced;
}
-
+
} // for all facts
-
+
return STATUS_Posted;
} // postLogic
@@ -821,7 +688,7 @@ public abstract class Doc
*/
private final String postCommit (String status)
{
- log.info("Sta=" + status + " DT=" + getDocumentType()
+ log.info("Sta=" + status + " DT=" + getDocumentType()
+ " ID=" + p_po.get_ID());
p_Status = status;
@@ -851,17 +718,9 @@ public abstract class Doc
}
}
}
- // Commit Doc
- if (!save(getTrxName())) // contains unlock & document status update
- {
- log.log(Level.SEVERE, "(doc not saved) ... rolling back");
- if (m_manageLocalTrx) {
- trx.rollback();
- trx.close();
- }
- unlock();
- return STATUS_Error;
- }
+
+ unlock();
+
// Success
if (m_manageLocalTrx) {
trx.commit(true);
@@ -899,7 +758,7 @@ public abstract class Doc
{
return m_trxName;
} // getTrxName
-
+
/**
* Unlock Document
*/
@@ -960,13 +819,13 @@ public abstract class Doc
finally
{
DB.close(rsDT, pstmt);
- rsDT = null;
+ rsDT = null;
pstmt = null;
}
}
if (m_DocumentType == null)
{
- log.log(Level.SEVERE, "No DocBaseType for C_DocType_ID="
+ log.log(Level.SEVERE, "No DocBaseType for C_DocType_ID="
+ getC_DocType_ID() + ", DocumentNo=" + getDocumentNo());
}
@@ -1021,7 +880,7 @@ public abstract class Doc
throw new IllegalStateException("Document Type not found");
} // setDocumentType
-
+
/**************************************************************************
* Is the Source Document Balanced
* @return true if (source) balanced
@@ -1109,7 +968,7 @@ public abstract class Doc
{
if (m_period != null)
return;
-
+
// Period defined in GL Journal (e.g. adjustment period)
int index = p_po.get_ColumnIndex("C_Period_ID");
if (index != -1)
@@ -1121,13 +980,13 @@ public abstract class Doc
if (m_period == null)
m_period = MPeriod.get(getCtx(), getDateAcct(), getAD_Org_ID());
// Is Period Open?
- if (m_period != null
+ if (m_period != null
&& m_period.isOpen(getDocumentType(), getDateAcct()))
m_C_Period_ID = m_period.getC_Period_ID();
else
m_C_Period_ID = -1;
//
- log.fine( // + AD_Client_ID + " - "
+ log.fine( // + AD_Client_ID + " - "
getDateAcct() + " - " + getDocumentType() + " => " + m_C_Period_ID);
} // setC_Period_ID
@@ -1234,7 +1093,7 @@ public abstract class Doc
}
return m_qty;
} // getQty
-
+
/*************************************************************************/
/** Account Type - Invoice - Charge */
@@ -1372,7 +1231,7 @@ public abstract class Doc
sql = "SELECT B_PaymentSelect_Acct FROM C_BankAccount_Acct WHERE C_BankAccount_ID=? AND C_AcctSchema_ID=?";
para_1 = getC_BankAccount_ID();
}
-
+
/** Account Type - Allocation */
else if (AcctType == ACCTTYPE_DiscountExp)
{
@@ -1545,25 +1404,6 @@ public abstract class Doc
return acct;
} // getAccount
-
- /**************************************************************************
- * Save to Disk - set posted flag
- * @param trxName transaction name
- * @return true if saved
- */
- private final boolean save (String trxName)
- {
- log.fine(toString() + "->" + p_Status);
-
- StringBuffer sql = new StringBuffer("UPDATE ");
- sql.append(get_TableName()).append(" SET Posted='").append(p_Status)
- .append("',Processing='N' ")
- .append("WHERE ")
- .append(get_TableName()).append("_ID=").append(p_po.get_ID());
- int no = DB.executeUpdate(sql.toString(), trxName);
- return no == 1;
- } // save
-
/**
* Get DocLine with ID
* @param Record_ID Record ID
@@ -1591,7 +1431,7 @@ public abstract class Doc
return p_po.toString();
} // toString
-
+
/**
* Get AD_Client_ID
* @return client
@@ -1600,7 +1440,7 @@ public abstract class Doc
{
return p_po.getAD_Client_ID();
} // getAD_Client_ID
-
+
/**
* Get AD_Org_ID
* @return org
@@ -1626,7 +1466,7 @@ public abstract class Doc
m_DocumentNo = (String)p_po.get_Value(index);
return m_DocumentNo;
} // getDocumentNo
-
+
/**
* Get Description
* @return Description
@@ -1643,7 +1483,7 @@ public abstract class Doc
}
return m_Description;
} // getDescription
-
+
/**
* Get C_Currency_ID
* @return currency
@@ -1664,7 +1504,7 @@ public abstract class Doc
}
return m_C_Currency_ID;
} // getC_Currency_ID
-
+
/**
* Set C_Currency_ID
* @param C_Currency_ID id
@@ -1673,7 +1513,7 @@ public abstract class Doc
{
m_C_Currency_ID = C_Currency_ID;
} // setC_Currency_ID
-
+
/**
* Is Multi Currency
* @return mc
@@ -1691,7 +1531,7 @@ public abstract class Doc
{
m_MultiCurrency = mc;
} // setIsMultiCurrency
-
+
/**
* Is Tax Included
* @return tax incl
@@ -1709,7 +1549,7 @@ public abstract class Doc
{
m_TaxIncluded = ti;
} // setIsTaxIncluded
-
+
/**
* Get C_ConversionType_ID
* @return ConversionType
@@ -1725,7 +1565,7 @@ public abstract class Doc
}
return 0;
} // getC_ConversionType_ID
-
+
/**
* Get GL_Category_ID
* @return category
@@ -1734,7 +1574,7 @@ public abstract class Doc
{
return m_GL_Category_ID;
} // getGL_Category_ID
-
+
/**
* Get GL_Category_ID
* @return category
@@ -1777,7 +1617,7 @@ public abstract class Doc
{
m_DateAcct = da;
} // setDateAcct
-
+
/**
* Get Document Date
* @return currency
@@ -1797,7 +1637,7 @@ public abstract class Doc
}
throw new IllegalStateException("No DateDoc");
} // getDateDoc
-
+
/**
* Set Date Doc
* @param dd document date
@@ -1824,7 +1664,7 @@ public abstract class Doc
}
throw new IllegalStateException("No Posted");
} // isPosted
-
+
/**
* Is Sales Trx
* @return true if posted
@@ -1867,7 +1707,7 @@ public abstract class Doc
}
return 0;
} // getC_DocType_ID
-
+
/**
* Get header level C_Charge_ID
* @return Charge
@@ -1899,7 +1739,7 @@ public abstract class Doc
}
return 0;
} // getSalesRep_ID
-
+
/**
* Get C_BankAccount_ID
* @return BankAccount
@@ -1929,7 +1769,7 @@ public abstract class Doc
{
m_C_BankAccount_ID = C_BankAccount_ID;
} // setC_BankAccount_ID
-
+
/**
* Get C_CashBook_ID
* @return CashBook
@@ -1976,7 +1816,7 @@ public abstract class Doc
return 0;
} // getM_Warehouse_ID
-
+
/**
* Get C_BPartner_ID
* @return BPartner
@@ -2006,7 +1846,7 @@ public abstract class Doc
{
m_C_BPartner_ID = C_BPartner_ID;
} // setC_BPartner_ID
-
+
/**
* Get C_BPartner_Location_ID
* @return BPartner Location
@@ -2038,7 +1878,7 @@ public abstract class Doc
}
return 0;
} // getC_Project_ID
-
+
/**
* Get C_ProjectPhase_ID
* @return Project Phase
@@ -2054,7 +1894,7 @@ public abstract class Doc
}
return 0;
} // getC_ProjectPhase_ID
-
+
/**
* Get C_ProjectTask_ID
* @return Project Task
@@ -2070,7 +1910,7 @@ public abstract class Doc
}
return 0;
} // getC_ProjectTask_ID
-
+
/**
* Get C_SalesRegion_ID
* @return Sales Region
@@ -2086,7 +1926,7 @@ public abstract class Doc
}
return 0;
} // getC_SalesRegion_ID
-
+
/**
* Get C_SalesRegion_ID
* @return Sales Region
@@ -2116,7 +1956,7 @@ public abstract class Doc
{
m_BP_C_SalesRegion_ID = C_SalesRegion_ID;
} // setBP_C_SalesRegion_ID
-
+
/**
* Get C_Activity_ID
* @return Activity
@@ -2189,7 +2029,7 @@ public abstract class Doc
{
return m_C_LocFrom_ID;
} // getC_LocFrom_ID
-
+
/**
* Set C_LocFrom_ID
* @param C_LocFrom_ID loc from
@@ -2232,7 +2072,7 @@ public abstract class Doc
}
return 0;
} // getUser1_ID
-
+
/**
* Get User2_ID
* @return Campaign
@@ -2248,7 +2088,7 @@ public abstract class Doc
}
return 0;
} // getUser2_ID
-
+
/**
* Get User Defined value
* @return User defined
@@ -2264,8 +2104,8 @@ public abstract class Doc
}
return 0;
} // getValue
-
-
+
+
/*************************************************************************/
// To be overwritten by Subclasses
@@ -2295,60 +2135,4 @@ public abstract class Doc
public ArrayList getFacts() {
return m_fact;
}
-
- /*
- * Array of tables with Post column
- */
- public static int[] getDocumentsTableID() {
- fillDocumentsTableArrays();
- return documentsTableID;
- }
-
- public static String[] getDocumentsTableName() {
- fillDocumentsTableArrays();
- return documentsTableName;
- }
-
- private static void fillDocumentsTableArrays() {
- if (documentsTableID == null) {
- String sql = "SELECT t.AD_Table_ID, t.TableName " +
- "FROM AD_Table t, AD_Column c " +
- "WHERE t.AD_Table_ID=c.AD_Table_ID AND " +
- "c.ColumnName='Posted' AND " +
- "IsView='N' " +
- "ORDER BY t.AD_Table_ID";
- ArrayList tableIDs = new ArrayList();
- ArrayList tableNames = new ArrayList();
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try
- {
- pstmt = DB.prepareStatement(sql, null);
- rs = pstmt.executeQuery();
- while (rs.next())
- {
- tableIDs.add(rs.getInt(1));
- tableNames.add(rs.getString(2));
- }
- }
- catch (SQLException e)
- {
- throw new DBException(e, sql);
- }
- finally
- {
- DB.close(rs, pstmt);
- rs = null; pstmt = null;
- }
- // Convert to array
- documentsTableID = new int[tableIDs.size()];
- documentsTableName = new String[tableIDs.size()];
- for (int i = 0; i < documentsTableID.length; i++)
- {
- documentsTableID[i] = tableIDs.get(i);
- documentsTableName[i] = tableNames.get(i);
- }
- }
- }
-
} // Doc
diff --git a/org.adempiere.base/src/org/compiere/acct/DocManager.java b/org.adempiere.base/src/org/compiere/acct/DocManager.java
new file mode 100644
index 0000000000..26c6801bab
--- /dev/null
+++ b/org.adempiere.base/src/org/compiere/acct/DocManager.java
@@ -0,0 +1,370 @@
+/******************************************************************************
+ * 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.acct;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.adempiere.base.IDocFactory;
+import org.adempiere.base.Service;
+import org.adempiere.base.ServiceQuery;
+import org.adempiere.exceptions.AdempiereException;
+import org.adempiere.exceptions.DBException;
+import org.compiere.model.MAcctSchema;
+import org.compiere.model.MTable;
+import org.compiere.util.AdempiereUserError;
+import org.compiere.util.CLogger;
+import org.compiere.util.DB;
+import org.compiere.util.Env;
+import org.compiere.util.Trx;
+import org.compiere.util.ValueNamePair;
+
+/**
+ * This class contains methods to manage the posting of financial document. Most of the code is adapted from the legacy code in Doc.java
+ * @author Jorg Janke
+ * @author hengsin
+ *
+ */
+public class DocManager {
+
+ private final static CLogger s_log = CLogger.getCLogger(DocManager.class);
+
+ /** AD_Table_ID's of documents */
+ private static int[] documentsTableID = null;
+
+ /** Table Names of documents */
+ private static String[] documentsTableName = null;
+
+ /*
+ * Array of tables with Post column
+ */
+ public static int[] getDocumentsTableID() {
+ fillDocumentsTableArrays();
+ return documentsTableID;
+ }
+
+ public static String[] getDocumentsTableName() {
+ fillDocumentsTableArrays();
+ return documentsTableName;
+ }
+
+ private static void fillDocumentsTableArrays() {
+ if (documentsTableID == null) {
+ String sql = "SELECT t.AD_Table_ID, t.TableName " +
+ "FROM AD_Table t, AD_Column c " +
+ "WHERE t.AD_Table_ID=c.AD_Table_ID AND " +
+ "c.ColumnName='Posted' AND " +
+ "IsView='N' " +
+ "ORDER BY t.AD_Table_ID";
+ ArrayList tableIDs = new ArrayList();
+ ArrayList tableNames = new ArrayList();
+ PreparedStatement pstmt = null;
+ ResultSet rs = null;
+ try
+ {
+ pstmt = DB.prepareStatement(sql, null);
+ rs = pstmt.executeQuery();
+ while (rs.next())
+ {
+ tableIDs.add(rs.getInt(1));
+ tableNames.add(rs.getString(2));
+ }
+ }
+ catch (SQLException e)
+ {
+ throw new DBException(e, sql);
+ }
+ finally
+ {
+ DB.close(rs, pstmt);
+ rs = null; pstmt = null;
+ }
+ // Convert to array
+ documentsTableID = new int[tableIDs.size()];
+ documentsTableName = new String[tableIDs.size()];
+ for (int i = 0; i < documentsTableID.length; i++)
+ {
+ documentsTableID[i] = tableIDs.get(i);
+ documentsTableName[i] = tableNames.get(i);
+ }
+ }
+ }
+
+ /**
+ * Create Posting document
+ * @param as accounting schema
+ * @param AD_Table_ID Table ID of Documents
+ * @param Record_ID record ID to load
+ * @param trxName transaction name
+ * @return Document or null
+ */
+ public static Doc getDocument(MAcctSchema as, int AD_Table_ID, int Record_ID, String trxName)
+ {
+ String TableName = null;
+ for (int i = 0; i < DocManager.getDocumentsTableID().length; i++)
+ {
+ if (DocManager.getDocumentsTableID()[i] == AD_Table_ID)
+ {
+ TableName = DocManager.getDocumentsTableName()[i];
+ break;
+ }
+ }
+ if (TableName == null)
+ {
+ s_log.severe("Not found AD_Table_ID=" + AD_Table_ID);
+ return null;
+ }
+
+ ServiceQuery query = new ServiceQuery();
+ query.put("gaap", as.getGAAP());
+ List factoryList = Service.list(IDocFactory.class, query);
+ if (factoryList != null)
+ {
+ for(IDocFactory factory : factoryList)
+ {
+ Doc doc = factory.getDocument(as, AD_Table_ID, Record_ID, trxName);
+ if (doc != null)
+ return doc;
+ }
+ }
+
+ query.clear();
+ query.put("gaap", "*");
+ factoryList = Service.list(IDocFactory.class, query);
+ if (factoryList != null)
+ {
+ for(IDocFactory factory : factoryList)
+ {
+ Doc doc = factory.getDocument(as, AD_Table_ID, Record_ID, trxName);
+ if (doc != null)
+ return doc;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Create Posting document
+ * @param as accounting schema
+ * @param AD_Table_ID Table ID of Documents
+ * @param rs ResultSet
+ * @param trxName transaction name
+ * @return Document
+ * @throws AdempiereUserError
+ */
+ public static Doc getDocument(MAcctSchema as, int AD_Table_ID, ResultSet rs, String trxName)
+ {
+ ServiceQuery query = new ServiceQuery();
+ query.put("gaap", as.getGAAP());
+ List factoryList = Service.list(IDocFactory.class,query);
+ if (factoryList != null)
+ {
+ for(IDocFactory factory : factoryList)
+ {
+ Doc doc = factory.getDocument(as, AD_Table_ID, rs, trxName);
+ if (doc != null)
+ return doc;
+ }
+ }
+
+ query.clear();
+ query.put("gaap", "*");
+ factoryList = Service.list(IDocFactory.class,query);
+ if (factoryList != null)
+ {
+ for(IDocFactory factory : factoryList)
+ {
+ Doc doc = factory.getDocument(as, AD_Table_ID, rs, trxName);
+ if (doc != null)
+ return doc;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Post Document
+ * @param ass accounting schema
+ * @param AD_Table_ID Transaction table
+ * @param Record_ID Record ID of this document
+ * @param force force posting
+ * @param repost Repost document
+ * @param trxName transaction
+ * @return null if the document was posted or error message
+ */
+ public static String postDocument(MAcctSchema[] ass,
+ int AD_Table_ID, int Record_ID, boolean force, boolean repost, String trxName) {
+
+ String tableName = null;
+ for (int i = 0; i < getDocumentsTableID().length; i++)
+ {
+ if (getDocumentsTableID()[i] == AD_Table_ID)
+ {
+ tableName = getDocumentsTableName()[i];
+ break;
+ }
+ }
+ if (tableName == null)
+ {
+ s_log.severe("Table not a financial document. AD_Table_ID=" + AD_Table_ID);
+ return "Table not a financial document. AD_Table_ID="+AD_Table_ID;
+ }
+
+ StringBuffer sql = new StringBuffer("SELECT * FROM ")
+ .append(tableName)
+ .append(" WHERE ").append(tableName).append("_ID=? AND Processed='Y'");
+ PreparedStatement pstmt = null;
+ ResultSet rs = null;
+ try
+ {
+ pstmt = DB.prepareStatement (sql.toString(), trxName);
+ pstmt.setInt (1, Record_ID);
+ rs = pstmt.executeQuery ();
+ if (rs.next ())
+ {
+ return postDocument(ass, AD_Table_ID, rs, force, repost, trxName);
+ }
+ else
+ {
+ s_log.severe("Not Found: " + tableName + "_ID=" + Record_ID);
+ return "NoDoc";
+ }
+ }
+ catch (Exception e)
+ {
+ if (e instanceof RuntimeException)
+ throw (RuntimeException)e;
+ else
+ throw new AdempiereException(e);
+ }
+ finally
+ {
+ DB.close(rs, pstmt);
+ rs = null;
+ pstmt = null;
+ }
+ }
+
+ /**
+ * Post Document
+ * @param ass accounting schema
+ * @param AD_Table_ID Transaction table
+ * @param rs Result set
+ * @param force force posting
+ * @param repost Repost document
+ * @param trxName transaction
+ * @return null if the document was posted or error message
+ */
+ public static String postDocument(MAcctSchema[] ass,
+ int AD_Table_ID, ResultSet rs, boolean force, boolean repost, String trxName) {
+ String localTrxName = null;
+ if (trxName == null)
+ {
+ localTrxName = Trx.createTrxName("Post");
+ trxName = localTrxName;
+ }
+
+ String error = null;
+ try
+ {
+ String status = "";
+ for(MAcctSchema as : ass)
+ {
+ Doc doc = Doc.get (as, AD_Table_ID, rs, trxName);
+ if (doc != null)
+ {
+ error = doc.post (force, repost); // repost
+ status = doc.getPostStatus();
+ if (error != null && error.trim().length() > 0)
+ break;
+ }
+ else
+ {
+ return "NoDoc";
+ }
+ }
+
+ MTable table = MTable.get(Env.getCtx(), AD_Table_ID);
+ int Record_ID = rs.getInt(table.getKeyColumns()[0]);
+ // Commit Doc
+ if (!save(trxName, AD_Table_ID, Record_ID, status))
+ {
+ ValueNamePair dbError = CLogger.retrieveError();
+ // log.log(Level.SEVERE, "(doc not saved) ... rolling back");
+ if (localTrxName != null) {
+ Trx trx = Trx.get(localTrxName, false);
+ if (trx != null)
+ trx.rollback();
+ }
+ if (dbError != null)
+ error = dbError.getValue();
+ else
+ error = "SaveError";
+ }
+ if (localTrxName != null) {
+ Trx trx = Trx.get(localTrxName, false);
+ if (trx != null)
+ trx.commit();
+ }
+ }
+ catch (Exception e)
+ {
+ if (localTrxName != null) {
+ Trx trx = Trx.get(localTrxName, false);
+ if (trx != null)
+ trx.rollback();
+ }
+ if (e instanceof RuntimeException)
+ throw (RuntimeException) e;
+ else
+ throw new AdempiereException(e);
+ }
+ finally
+ {
+ if (localTrxName != null)
+ {
+ Trx trx = Trx.get(localTrxName, false);
+ if (trx != null)
+ trx.close();
+ }
+ }
+ return error;
+ }
+
+ /**************************************************************************
+ * Save to Disk - set posted flag
+ * @param trxName transaction name
+ * @return true if saved
+ */
+ private final static boolean save (String trxName, int AD_Table_ID, int Record_ID, String status)
+ {
+ MTable table = MTable.get(Env.getCtx(), AD_Table_ID);
+ StringBuffer sql = new StringBuffer("UPDATE ");
+ sql.append(table.getTableName()).append(" SET Posted='").append(status)
+ .append("',Processing='N' ")
+ .append("WHERE ")
+ .append(table.getTableName()).append("_ID=").append(Record_ID);
+ CLogger.resetLast();
+ int no = DB.executeUpdate(sql.toString(), trxName);
+ return no == 1;
+ } // save
+}
diff --git a/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java b/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java
index d206519bbd..f0edb20a2d 100644
--- a/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java
+++ b/org.adempiere.base/src/org/compiere/acct/Doc_AllocationHdr.java
@@ -46,26 +46,26 @@ import org.compiere.util.Env;
*
* @author Jorg Janke
* @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $
- *
- * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
+ *
+ * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
* Avoid posting if Receipt and both accounts Unallocated Cash and Receivable are equal
* Avoid posting if Payment and both accounts Payment Select and Liability are equal
- *
+ *
* @author phib
* BF [ 2019262 ] Allocation posting currency gain/loss omits line reference
- *
+ *
*/
public class Doc_AllocationHdr extends Doc
{
/**
* Constructor
- * @param ass accounting schemata
+ * @param as accounting schema
* @param rs record
* @param trxName trx
*/
- public Doc_AllocationHdr (MAcctSchema[] ass, ResultSet rs, String trxName)
+ public Doc_AllocationHdr (MAcctSchema as, ResultSet rs, String trxName)
{
- super (ass, MAllocationHdr.class, rs, DOCTYPE_Allocation, trxName);
+ super (as, MAllocationHdr.class, rs, DOCTYPE_Allocation, trxName);
} // Doc_Allocation
/** Tolerance G&L */
@@ -100,7 +100,7 @@ public class Doc_AllocationHdr extends Doc
{
MAllocationLine line = lines[i];
DocLine_Allocation docLine = new DocLine_Allocation(line, this);
-
+
// Get Payment Conversion Rate
if (line.getC_Payment_ID() != 0)
{
@@ -119,7 +119,7 @@ public class Doc_AllocationHdr extends Doc
return dls;
} // loadLines
-
+
/**************************************************************************
* Get Source Currency Balance - subtracts line and tax amounts from total - no rounding
* @return positive amount, if total invoice is bigger than lines
@@ -145,7 +145,7 @@ public class Doc_AllocationHdr extends Doc
* DiscountExp DR
* WriteOff DR
* Receivables CR
- *
+ *
* AP_Invoice_Payment
* Liability DR
* DiscountRev CR
@@ -163,7 +163,7 @@ public class Doc_AllocationHdr extends Doc
* Realized Gain & Loss
* AR/AP DR CR
* Realized G/L DR CR
- *
+ *
*
*
* Tax needs to be corrected for discount & write-off;
@@ -184,15 +184,15 @@ public class Doc_AllocationHdr extends Doc
{
DocLine_Allocation line = (DocLine_Allocation)p_lines[i];
setC_BPartner_ID(line.getC_BPartner_ID());
-
+
// CashBankTransfer - all references null and Discount/WriteOff = 0
- if (line.getC_Payment_ID() != 0
+ if (line.getC_Payment_ID() != 0
&& line.getC_Invoice_ID() == 0 && line.getC_Order_ID() == 0
&& line.getC_CashLine_ID() == 0 && line.getC_BPartner_ID() == 0
&& Env.ZERO.compareTo(line.getDiscountAmt()) == 0
&& Env.ZERO.compareTo(line.getWriteOffAmt()) == 0)
continue;
-
+
// Receivables/Liability Amt
BigDecimal allocationSource = line.getAmtSource()
.add(line.getDiscountAmt())
@@ -211,7 +211,7 @@ public class Doc_AllocationHdr extends Doc
MInvoice invoice = null;
if (line.getC_Invoice_ID() != 0)
invoice = new MInvoice (getCtx(), line.getC_Invoice_ID(), getTrxName());
-
+
// No Invoice
if (invoice == null)
{
@@ -230,32 +230,32 @@ public class Doc_AllocationHdr extends Doc
return null;
}
}
- // Sales Invoice
+ // Sales Invoice
else if (invoice.isSOTrx())
{
// Avoid usage of clearing accounts
// If both accounts Unallocated Cash and Receivable are equal
// then don't post
-
+
MAccount acct_unallocated_cash = null;
if (line.getC_Payment_ID() != 0)
- acct_unallocated_cash = getPaymentAcct(as, line.getC_Payment_ID());
+ acct_unallocated_cash = getPaymentAcct(as, line.getC_Payment_ID());
else if (line.getC_CashLine_ID() != 0)
acct_unallocated_cash = getCashAcct(as, line.getC_CashLine_ID());
MAccount acct_receivable = getAccount(Doc.ACCTTYPE_C_Receivable, as);
-
+
if ((!as.isPostIfClearingEqual()) && acct_unallocated_cash != null && acct_unallocated_cash.equals(acct_receivable) && (!isInterOrg)) {
-
+
// if not using clearing accounts, then don't post amtsource
// change the allocationsource to be writeoff + discount
allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt());
-
+
} else {
-
+
// Normal behavior -- unchanged if using clearing accounts
-
+
// Payment/Cash DR
if (line.getC_Payment_ID() != 0)
{
@@ -275,7 +275,7 @@ public class Doc_AllocationHdr extends Doc
}
// End Avoid usage of clearing accounts
-
+
// Discount DR
if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0)
{
@@ -292,27 +292,27 @@ public class Doc_AllocationHdr extends Doc
if (fl != null && payment != null)
fl.setAD_Org_ID(payment.getAD_Org_ID());
}
-
+
// AR Invoice Amount CR
if (as.isAccrual())
{
bpAcct = getAccount(Doc.ACCTTYPE_C_Receivable, as);
fl = fact.createLine (line, bpAcct,
- getC_Currency_ID(), null, allocationSource); // payment currency
+ getC_Currency_ID(), null, allocationSource); // payment currency
if (fl != null)
allocationAccounted = fl.getAcctBalance().negate();
if (fl != null && invoice != null)
fl.setAD_Org_ID(invoice.getAD_Org_ID());
-
+
// for Realized Gain & Loss
flForRGL = factForRGL.createLine (line, bpAcct,
- getC_Currency_ID(), null, allocationSourceForRGL); // payment currency
+ getC_Currency_ID(), null, allocationSourceForRGL); // payment currency
if (flForRGL != null)
allocationAccountedForRGL = flForRGL.getAcctBalance().negate();
}
else // Cash Based
{
- allocationAccounted = createCashBasedAcct (as, fact,
+ allocationAccounted = createCashBasedAcct (as, fact,
invoice, allocationSource);
allocationAccountedForRGL = allocationAccounted;
}
@@ -331,12 +331,12 @@ public class Doc_AllocationHdr extends Doc
acct_payment_select = getCashAcct(as, line.getC_CashLine_ID());
MAccount acct_liability = getAccount(Doc.ACCTTYPE_V_Liability, as);
boolean isUsingClearing = true;
-
+
// Save original allocation source for realized gain & loss purposes
allocationSourceForRGL = allocationSourceForRGL.negate();
-
+
if ((!as.isPostIfClearingEqual()) && acct_payment_select != null && acct_payment_select.equals(acct_liability) && (!isInterOrg)) {
-
+
// if not using clearing accounts, then don't post amtsource
// change the allocationsource to be writeoff + discount
allocationSource = line.getDiscountAmt().add(line.getWriteOffAmt());
@@ -344,7 +344,7 @@ public class Doc_AllocationHdr extends Doc
}
// End Avoid usage of clearing accounts
-
+
allocationSource = allocationSource.negate(); // allocation is negative
// AP Invoice Amount DR
if (as.isAccrual())
@@ -365,11 +365,11 @@ public class Doc_AllocationHdr extends Doc
}
else // Cash Based
{
- allocationAccounted = createCashBasedAcct (as, fact,
+ allocationAccounted = createCashBasedAcct (as, fact,
invoice, allocationSource);
allocationAccountedForRGL = allocationAccounted;
}
-
+
// Discount CR
if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0)
{
@@ -403,7 +403,7 @@ public class Doc_AllocationHdr extends Doc
fl.setAD_Org_ID(cashLine.getAD_Org_ID());
}
}
-
+
// VAT Tax Correction
if (invoice != null && as.isTaxCorrection())
{
@@ -415,8 +415,8 @@ public class Doc_AllocationHdr extends Doc
//
if (taxCorrectionAmt.signum() != 0)
{
- if (!createTaxCorrection(as, fact, line,
- getAccount(invoice.isSOTrx() ? Doc.ACCTTYPE_DiscountExp : Doc.ACCTTYPE_DiscountRev, as),
+ if (!createTaxCorrection(as, fact, line,
+ getAccount(invoice.isSOTrx() ? Doc.ACCTTYPE_DiscountExp : Doc.ACCTTYPE_DiscountRev, as),
getAccount(Doc.ACCTTYPE_WriteOff, as), invoice.isSOTrx()))
{
p_Error = "Cannot create Tax correction";
@@ -424,18 +424,18 @@ public class Doc_AllocationHdr extends Doc
}
}
}
-
+
// Realized Gain & Loss
if (invoice != null
&& (getC_Currency_ID() != as.getC_Currency_ID() // payment allocation in foreign currency
|| getC_Currency_ID() != line.getInvoiceC_Currency_ID())) // allocation <> invoice currency
{
- p_Error = createRealizedGainLoss (line, as, fact, bpAcct, invoice,
+ p_Error = createRealizedGainLoss (line, as, fact, bpAcct, invoice,
allocationSource, allocationAccounted);
if (p_Error != null)
return null;
}
-
+
} // for all lines
// FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
@@ -462,7 +462,7 @@ public class Doc_AllocationHdr extends Doc
fact.remove(factline);
}
}
-
+
// reset line info
setC_BPartner_ID(0);
//
@@ -479,12 +479,12 @@ public class Doc_AllocationHdr extends Doc
// no org element or not need to be balanced
return false;
}
-
+
if (p_lines.length <= 0) {
// no lines
return false;
}
-
+
int startorg = p_lines[0].getAD_Org_ID();
// validate if the allocation involves more than one org
for (int i = 0; i < p_lines.length; i++) {
@@ -513,20 +513,20 @@ public class Doc_AllocationHdr extends Doc
order = new MOrder (getCtx(), line.getC_Order_ID(), getTrxName());
orgorder = order.getAD_Org_ID();
}
-
- if ( line.getAD_Org_ID() != startorg
+
+ if ( line.getAD_Org_ID() != startorg
|| orgpayment != startorg
- || orginvoice != startorg
+ || orginvoice != startorg
|| orgcashline != startorg
|| orgorder != startorg)
return true;
}
-
+
return false;
}
/**
- * Compare the dimension ID's from two factlines
+ * Compare the dimension ID's from two factlines
* @param allEquals
* @param prevFactLine
* @param factLine
@@ -547,8 +547,8 @@ public class Doc_AllocationHdr extends Doc
&& factLine.getC_LocTo_ID() == prevFactLine.getC_LocTo_ID()
&& factLine.getC_Period_ID() == prevFactLine.getC_Period_ID()
&& factLine.getC_Project_ID() == prevFactLine.getC_Project_ID()
- && factLine.getC_ProjectPhase_ID() == prevFactLine.getC_ProjectPhase_ID()
- && factLine.getC_ProjectTask_ID() == prevFactLine.getC_ProjectTask_ID()
+ && factLine.getC_ProjectPhase_ID() == prevFactLine.getC_ProjectPhase_ID()
+ && factLine.getC_ProjectTask_ID() == prevFactLine.getC_ProjectTask_ID()
&& factLine.getC_SalesRegion_ID() == prevFactLine.getC_SalesRegion_ID()
&& factLine.getC_SubAcct_ID() == prevFactLine.getC_SubAcct_ID()
&& factLine.getC_Tax_ID() == prevFactLine.getC_Tax_ID()
@@ -559,7 +559,7 @@ public class Doc_AllocationHdr extends Doc
&& factLine.getM_Product_ID() == prevFactLine.getM_Product_ID()
&& factLine.getUserElement1_ID() == prevFactLine.getUserElement1_ID()
&& factLine.getUserElement2_ID() == prevFactLine.getUserElement2_ID()
- && factLine.getUser1_ID() == prevFactLine.getUser1_ID()
+ && factLine.getUser1_ID() == prevFactLine.getUser1_ID()
&& factLine.getUser2_ID() == prevFactLine.getUser2_ID());
}
@@ -571,7 +571,7 @@ public class Doc_AllocationHdr extends Doc
* @param allocationSource allocation amount (incl discount, writeoff)
* @return Accounted Amt
*/
- private BigDecimal createCashBasedAcct (MAcctSchema as, Fact fact, MInvoice invoice,
+ private BigDecimal createCashBasedAcct (MAcctSchema as, Fact fact, MInvoice invoice,
BigDecimal allocationSource)
{
BigDecimal allocationAccounted = Env.ZERO;
@@ -581,32 +581,32 @@ public class Doc_AllocationHdr extends Doc
percent = 1.0;
log.config("Multiplier=" + percent + " - GrandTotal=" + invoice.getGrandTotal()
+ " - Allocation Source=" + allocationSource);
-
+
// Get Invoice Postings
- Doc_Invoice docInvoice = (Doc_Invoice)Doc.get(new MAcctSchema[]{as},
+ Doc_Invoice docInvoice = (Doc_Invoice)Doc.get(as,
MInvoice.Table_ID, invoice.getC_Invoice_ID(), getTrxName());
docInvoice.loadDocumentDetails();
allocationAccounted = docInvoice.createFactCash(as, fact, new BigDecimal(percent));
log.config("Allocation Accounted=" + allocationAccounted);
-
- // Cash Based Commitment Release
+
+ // Cash Based Commitment Release
if (as.isCreatePOCommitment() && !invoice.isSOTrx())
{
MInvoiceLine[] lines = invoice.getLines();
for (int i = 0; i < lines.length; i++)
{
- Fact factC = Doc_Order.getCommitmentRelease(as, this,
+ Fact factC = Doc_Order.getCommitmentRelease(as, this,
lines[i].getQtyInvoiced(), lines[i].getC_InvoiceLine_ID(), new BigDecimal(percent));
if (factC == null)
return null;
m_facts.add(factC);
}
} // Commitment
-
+
return allocationAccounted;
} // createCashBasedAcct
-
+
/**
* Get Payment (Unallocated Payment or Payment Selection) Acct of Bank Account
* @param as accounting schema
@@ -616,7 +616,7 @@ public class Doc_AllocationHdr extends Doc
private MAccount getPaymentAcct (MAcctSchema as, int C_Payment_ID)
{
setC_BankAccount_ID(0);
- // Doc.ACCTTYPE_UnallocatedCash (AR) or C_Prepayment
+ // Doc.ACCTTYPE_UnallocatedCash (AR) or C_Prepayment
// or Doc.ACCTTYPE_PaymentSelect (AP) or V_Prepayment
int accountType = Doc.ACCTTYPE_UnallocatedCash;
//
@@ -644,7 +644,7 @@ public class Doc_AllocationHdr extends Doc
accountType = Doc.ACCTTYPE_V_Prepayment;
}
}
- }
+ }
catch (Exception e)
{
log.log(Level.SEVERE, sql, e);
@@ -654,7 +654,7 @@ public class Doc_AllocationHdr extends Doc
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
-
+
//
if (getC_BankAccount_ID() <= 0)
{
@@ -663,7 +663,7 @@ public class Doc_AllocationHdr extends Doc
}
return getAccount (accountType, as);
} // getPaymentAcct
-
+
/**
* Get Cash (Transfer) Acct of CashBook
* @param as accounting schema
@@ -683,7 +683,7 @@ public class Doc_AllocationHdr extends Doc
}
return getAccount(Doc.ACCTTYPE_CashTransfer, as);
} // getCashAcct
-
+
/**************************************************************************
* Create Realized Gain & Loss.
@@ -703,9 +703,9 @@ public class Doc_AllocationHdr extends Doc
BigDecimal invoiceSource = null;
BigDecimal invoiceAccounted = null;
//
- String sql = "SELECT "
- + (invoice.isSOTrx()
- ? "SUM(AmtSourceDr), SUM(AmtAcctDr)" // so
+ String sql = "SELECT "
+ + (invoice.isSOTrx()
+ ? "SUM(AmtSourceDr), SUM(AmtAcctDr)" // so
: "SUM(AmtSourceCr), SUM(AmtAcctCr)") // po
+ " FROM Fact_Acct "
+ "WHERE AD_Table_ID=318 AND Record_ID=?" // Invoice
@@ -744,13 +744,13 @@ public class Doc_AllocationHdr extends Doc
// Allocation not Invoice Currency
if (getC_Currency_ID() != invoice.getC_Currency_ID())
{
- BigDecimal allocationSourceNew = MConversionRate.convert(getCtx(),
- allocationSource, getC_Currency_ID(),
- invoice.getC_Currency_ID(), getDateAcct(),
+ BigDecimal allocationSourceNew = MConversionRate.convert(getCtx(),
+ allocationSource, getC_Currency_ID(),
+ invoice.getC_Currency_ID(), getDateAcct(),
invoice.getC_ConversionType_ID(), invoice.getAD_Client_ID(), invoice.getAD_Org_ID());
if (allocationSourceNew == null)
return "Gain/Loss - No Conversion from Allocation->Invoice";
- String d2 = "Allocation=(" + getC_Currency_ID() + ")" + allocationSource
+ String d2 = "Allocation=(" + getC_Currency_ID() + ")" + allocationSource
+ "->(" + invoice.getC_Currency_ID() + ")" + allocationSourceNew;
log.fine(d2);
description += " - " + d2;
@@ -785,22 +785,22 @@ public class Doc_AllocationHdr extends Doc
log.fine(d2);
description += " - " + d2;
}
-
+
if (acctDifference.signum() == 0)
{
log.fine("No Difference");
return null;
}
-
+
MAccount gain = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedGain_Acct());
MAccount loss = MAccount.get (as.getCtx(), as.getAcctSchemaDefault().getRealizedLoss_Acct());
//
if (invoice.isSOTrx())
{
- FactLine fl = fact.createLine (line, loss, gain,
+ FactLine fl = fact.createLine (line, loss, gain,
as.getC_Currency_ID(), acctDifference);
fl.setDescription(description);
- fact.createLine (line, acct,
+ fact.createLine (line, acct,
as.getC_Currency_ID(), acctDifference.negate());
fl.setDescription(description);
}
@@ -808,7 +808,7 @@ public class Doc_AllocationHdr extends Doc
{
fact.createLine (line, acct,
as.getC_Currency_ID(), acctDifference);
- FactLine fl = fact.createLine (line, loss, gain,
+ FactLine fl = fact.createLine (line, loss, gain,
as.getC_Currency_ID(), acctDifference.negate());
}
return null;
@@ -823,8 +823,8 @@ public class Doc_AllocationHdr extends Doc
* Example:
* Invoice: Net $100 + Tax1 $15 + Tax2 $5 = Total $120
* Payment: $115 (i.e. $5 underpayment)
- * Tax Adjustment = Tax1 = 0.63 (15/120*5) Tax2 = 0.21 (5/120/5)
- *
+ * Tax Adjustment = Tax1 = 0.63 (15/120*5) Tax2 = 0.21 (5/120/5)
+ *
* @param as accounting schema
* @param fact fact
* @param line Allocation line
@@ -832,7 +832,7 @@ public class Doc_AllocationHdr extends Doc
* @param WriteOffAccoint write off acct
* @return true if created
*/
- private boolean createTaxCorrection (MAcctSchema as, Fact fact,
+ private boolean createTaxCorrection (MAcctSchema as, Fact fact,
DocLine_Allocation line,
MAccount DiscountAccount, MAccount WriteOffAccoint, boolean isSOTrx)
{
@@ -843,10 +843,10 @@ public class Doc_AllocationHdr extends Doc
BigDecimal writeOff = Env.ZERO;
if (as.isTaxCorrectionWriteOff())
writeOff = line.getWriteOffAmt();
-
+
Doc_AllocationTax tax = new Doc_AllocationTax (
DiscountAccount, discount, WriteOffAccoint, writeOff, isSOTrx);
-
+
// Get Source Amounts with account
String sql = "SELECT * "
+ "FROM Fact_Acct "
@@ -882,14 +882,14 @@ public class Doc_AllocationHdr extends Doc
if (tax.getLineCount() < 2)
return true;
return tax.createEntries (as, fact, line);
-
+
} // createTaxCorrection
} // Doc_Allocation
/**
* Allocation Document Tax Handing
- *
+ *
* @author Jorg Janke
* @version $Id: Doc_Allocation.java,v 1.6 2006/07/30 00:53:33 jjanke Exp $
*/
@@ -931,7 +931,7 @@ class Doc_AllocationTax
{
m_facts.add(fact);
} // addInvoiceLine
-
+
/**
* Get Line Count
* @return number of lines
@@ -940,7 +940,7 @@ class Doc_AllocationTax
{
return m_facts.size();
} // getLineCount
-
+
/**
* Create Accounting Entries
* @param as account schema
@@ -958,15 +958,15 @@ class Doc_AllocationTax
if (factAcct.getAmtSourceDr().compareTo(total) > 0)
{
total = factAcct.getAmtSourceDr();
- m_totalIndex = i;
+ m_totalIndex = i;
}
if (factAcct.getAmtSourceCr().compareTo(total) > 0)
{
total = factAcct.getAmtSourceCr();
- m_totalIndex = i;
+ m_totalIndex = i;
}
}
-
+
MFactAcct factAcct = (MFactAcct)m_facts.get(m_totalIndex);
log.info ("Total Invoice = " + total + " - " + factAcct);
int precision = as.getStdPrecision();
@@ -975,10 +975,10 @@ class Doc_AllocationTax
// No Tax Line
if (i == m_totalIndex)
continue;
-
+
factAcct = (MFactAcct)m_facts.get(i);
log.info (i + ": " + factAcct);
-
+
// Create Tax Account
MAccount taxAcct = factAcct.getMAccount();
if (taxAcct == null || taxAcct.get_ID() == 0)
@@ -986,15 +986,15 @@ class Doc_AllocationTax
log.severe ("Tax Account not found/created");
return false;
}
-
-
-// Discount Amount
+
+
+// Discount Amount
if (m_DiscountAmt.signum() != 0)
{
// Original Tax is DR - need to correct it CR
if (Env.ZERO.compareTo(factAcct.getAmtSourceDr()) != 0)
{
- BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(),
+ BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(),
total, m_DiscountAmt, precision);
if (amount.signum() != 0)
{
@@ -1011,13 +1011,13 @@ class Doc_AllocationTax
fact.createLine (line, taxAcct,
as.getC_Currency_ID(), null, amount.negate());
}
-
+
}
}
// Original Tax is CR - need to correct it DR
else
{
- BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(),
+ BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(),
total, m_DiscountAmt, precision);
if (amount.signum() != 0)
{
@@ -1036,14 +1036,14 @@ class Doc_AllocationTax
}
}
} // Discount
-
- // WriteOff Amount
+
+ // WriteOff Amount
if (m_WriteOffAmt.signum() != 0)
{
// Original Tax is DR - need to correct it CR
if (Env.ZERO.compareTo(factAcct.getAmtSourceDr()) != 0)
{
- BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(),
+ BigDecimal amount = calcAmount(factAcct.getAmtSourceDr(),
total, m_WriteOffAmt, precision);
if (amount.signum() != 0)
{
@@ -1056,7 +1056,7 @@ class Doc_AllocationTax
// Original Tax is CR - need to correct it DR
else
{
- BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(),
+ BigDecimal amount = calcAmount(factAcct.getAmtSourceCr(),
total, m_WriteOffAmt, precision);
if (amount.signum() != 0)
{
@@ -1067,11 +1067,11 @@ class Doc_AllocationTax
}
}
} // WriteOff
-
+
} // for all lines
return true;
} // createEntries
-
+
/**
* Calc Amount tax / total * amt
* @param tax tax
@@ -1083,17 +1083,17 @@ class Doc_AllocationTax
private BigDecimal calcAmount (BigDecimal tax, BigDecimal total, BigDecimal amt, int precision)
{
log.fine("Amt=" + amt + " - Total=" + total + ", Tax=" + tax);
- if (tax.signum() == 0
+ if (tax.signum() == 0
|| total.signum() == 0
|| amt.signum() == 0)
return Env.ZERO;
//
- BigDecimal multiplier = tax.divide(total, 10, BigDecimal.ROUND_HALF_UP);
+ BigDecimal multiplier = tax.divide(total, 10, BigDecimal.ROUND_HALF_UP);
BigDecimal retValue = multiplier.multiply(amt);
if (retValue.scale() > precision)
retValue = retValue.setScale(precision, BigDecimal.ROUND_HALF_UP);
log.fine(retValue + " (Mult=" + multiplier + "(Prec=" + precision + ")");
return retValue;
} // calcAmount
-
+
} // Doc_AllocationTax
diff --git a/org.adempiere.base/src/org/compiere/acct/Doc_BankStatement.java b/org.adempiere.base/src/org/compiere/acct/Doc_BankStatement.java
index 762f8f716d..c687355495 100644
--- a/org.adempiere.base/src/org/compiere/acct/Doc_BankStatement.java
+++ b/org.adempiere.base/src/org/compiere/acct/Doc_BankStatement.java
@@ -36,27 +36,27 @@ import org.compiere.util.Env;
*
* @author Jorg Janke
* @version $Id: Doc_Bank.java,v 1.3 2006/07/30 00:53:33 jjanke Exp $
- *
- * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
+ *
+ * FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
* Avoid posting if both accounts BankAsset and BankInTransit are equal
* @author victor.perez@e-evolution.com, e-Evolution http://www.e-evolution.com
- *