Search in sources :

Example 1 with Doc

use of org.compiere.acct.Doc in project adempiere by adempiere.

the class AcctProcessor method postSession.

//	doWork
/**
	 * 	Post Session
	 */
private void postSession() {
    List<BigDecimal> listProcessedOn = new ArrayList<BigDecimal>();
    // to include potential null values
    listProcessedOn.add(Env.ZERO);
    //get current time from db
    Timestamp ts = DB.getSQLValueTS(null, "SELECT CURRENT_TIMESTAMP FROM DUAL");
    //go back 2 second to be safe (to avoid posting documents being completed at this precise moment)
    long ms = ts.getTime() - (2 * 1000);
    ts = new Timestamp(ms);
    long mili = ts.getTime();
    BigDecimal value = new BigDecimal(Long.toString(mili));
    //first pass, collect all ts (FR 2962094 - required for weighted average costing)
    int[] documentsTableID = Doc.getDocumentsTableID();
    String[] documentsTableName = Doc.getDocumentsTableName();
    for (int i = 0; i < documentsTableID.length; i++) {
        int AD_Table_ID = documentsTableID[i];
        String TableName = documentsTableName[i];
        //	Post only special documents
        if (m_model.getAD_Table_ID() != 0 && m_model.getAD_Table_ID() != AD_Table_ID)
            continue;
        StringBuffer sql = new StringBuffer("SELECT DISTINCT ProcessedOn FROM ").append(TableName).append(" WHERE AD_Client_ID=? AND ProcessedOn<?").append(" AND Processed='Y' AND Posted='N' AND IsActive='Y'");
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = DB.prepareStatement(sql.toString(), null);
            pstmt.setInt(1, m_model.getAD_Client_ID());
            pstmt.setBigDecimal(2, value);
            rs = pstmt.executeQuery();
            while (!isInterrupted() && rs.next()) {
                BigDecimal processedOn = rs.getBigDecimal(1);
                if (!listProcessedOn.contains(processedOn))
                    listProcessedOn.add(processedOn);
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, sql.toString(), e);
        } finally {
            DB.close(rs, pstmt);
        }
    }
    // initialize counters per table
    int[] count = new int[documentsTableID.length];
    int[] countError = new int[documentsTableID.length];
    for (int i = 0; i < count.length; i++) {
        count[i] = 0;
        countError[i] = 0;
    }
    //sort and post in the processed date order
    Collections.sort(listProcessedOn);
    for (BigDecimal processedOn : listProcessedOn) {
        for (int i = 0; i < documentsTableID.length; i++) {
            int AD_Table_ID = documentsTableID[i];
            String TableName = documentsTableName[i];
            //	Post only special documents
            if (m_model.getAD_Table_ID() != 0 && m_model.getAD_Table_ID() != AD_Table_ID)
                continue;
            //  SELECT * FROM table
            StringBuffer sql = new StringBuffer("SELECT * FROM ").append(TableName).append(" WHERE AD_Client_ID=? AND (ProcessedOn");
            if (processedOn.compareTo(Env.ZERO) != 0)
                sql.append("=?");
            else
                sql.append(" IS NULL OR ProcessedOn=0");
            sql.append(") AND Processed='Y' AND Posted='N' AND IsActive='Y'").append(" ORDER BY Created");
            //
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                pstmt = DB.prepareStatement(sql.toString(), null);
                pstmt.setInt(1, m_model.getAD_Client_ID());
                if (processedOn.compareTo(Env.ZERO) != 0)
                    pstmt.setBigDecimal(2, processedOn);
                rs = pstmt.executeQuery();
                while (!isInterrupted() && rs.next()) {
                    count[i]++;
                    boolean ok = true;
                    try {
                        Doc doc = Doc.get(m_ass, AD_Table_ID, rs, null);
                        if (doc == null) {
                            log.severe(getName() + ": No Doc for " + TableName);
                            ok = false;
                        } else {
                            //  post no force/repost
                            String error = doc.post(false, false);
                            ok = error == null;
                        }
                    } catch (Exception e) {
                        log.log(Level.SEVERE, getName() + ": " + TableName, e);
                        ok = false;
                    }
                    if (!ok)
                        countError[i]++;
                }
                rs.close();
            } catch (Exception e) {
                log.log(Level.SEVERE, sql.toString(), e);
            } finally {
                DB.close(rs, pstmt);
            }
        }
    // for tableID
    }
    for (int i = 0; i < documentsTableID.length; i++) {
        String TableName = documentsTableName[i];
        if (count[i] > 0) {
            m_summary.append(TableName).append("=").append(count[i]);
            if (countError[i] > 0)
                m_summary.append("(Errors=").append(countError[i]).append(")");
            m_summary.append(" - ");
            log.finer(getName() + ": " + m_summary.toString());
        } else
            log.finer(getName() + ": " + TableName + " - no work");
    }
}
Also used : ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) ResultSet(java.sql.ResultSet) Doc(org.compiere.acct.Doc)

Example 2 with Doc

use of org.compiere.acct.Doc in project lar_361 by comitsrl.

the class LCO_Validator method accountingForInvoiceWithholdingOnPayment.

private String accountingForInvoiceWithholdingOnPayment(MAllocationHdr ah) {
    // Accounting like Doc_Allocation
    // (Write off) vs (invoice withholding where iscalconpayment=Y)
    // 20070807 - globalqss - instead of adding a new WriteOff post, find the
    // current WriteOff and subtract from the posting
    Doc doc = ah.getDoc();
    ArrayList<Fact> facts = doc.getFacts();
    // one fact per acctschema
    for (int i = 0; i < facts.size(); i++) {
        Fact fact = facts.get(i);
        MAcctSchema as = fact.getAcctSchema();
        MAllocationLine[] alloc_lines = ah.getLines(false);
        for (int j = 0; j < alloc_lines.length; j++) {
            BigDecimal tottax = new BigDecimal(0);
            MAllocationLine alloc_line = alloc_lines[j];
            doc.setC_BPartner_ID(alloc_line.getC_BPartner_ID());
            int inv_id = alloc_line.getC_Invoice_ID();
            if (inv_id <= 0)
                continue;
            MInvoice invoice = null;
            invoice = new MInvoice(ah.getCtx(), alloc_line.getC_Invoice_ID(), ah.get_TrxName());
            if (invoice == null || invoice.getC_Invoice_ID() == 0)
                continue;
            String sql = "SELECT i.C_Tax_ID, NVL(SUM(i.TaxBaseAmt),0) AS TaxBaseAmt, NVL(SUM(i.TaxAmt),0) AS TaxAmt, t.Name, t.Rate, t.IsSalesTax " + " FROM LCO_InvoiceWithholding i, C_Tax t " + " WHERE i.C_Invoice_ID = ? AND " + "i.IsCalcOnPayment = 'Y' AND " + "i.IsActive = 'Y' AND " + "i.Processed = 'Y' AND " + "i.C_AllocationLine_ID = ? AND " + "i.C_Tax_ID = t.C_Tax_ID " + "GROUP BY i.C_Tax_ID, t.Name, t.Rate, t.IsSalesTax";
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                pstmt = DB.prepareStatement(sql, ah.get_TrxName());
                pstmt.setInt(1, invoice.getC_Invoice_ID());
                pstmt.setInt(2, alloc_line.getC_AllocationLine_ID());
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    int tax_ID = rs.getInt(1);
                    BigDecimal taxBaseAmt = rs.getBigDecimal(2);
                    BigDecimal amount = rs.getBigDecimal(3);
                    String name = rs.getString(4);
                    BigDecimal rate = rs.getBigDecimal(5);
                    boolean salesTax = rs.getString(6).equals("Y") ? true : false;
                    DocTax taxLine = new DocTax(tax_ID, name, rate, taxBaseAmt, amount, salesTax);
                    if (amount != null && amount.signum() != 0) {
                        FactLine tl = null;
                        if (invoice.isSOTrx()) {
                            tl = fact.createLine(null, taxLine.getAccount(DocTax.ACCTTYPE_TaxDue, as), as.getC_Currency_ID(), amount, null);
                        } else {
                            tl = fact.createLine(null, taxLine.getAccount(taxLine.getAPTaxType(), as), as.getC_Currency_ID(), null, amount);
                        }
                        if (tl != null)
                            tl.setC_Tax_ID(taxLine.getC_Tax_ID());
                        tottax = tottax.add(amount);
                    }
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, sql, e);
                return "Error posting C_InvoiceTax from LCO_InvoiceWithholding";
            } finally {
                DB.close(rs, pstmt);
                rs = null;
                pstmt = null;
            }
            // Write off		DR
            if (Env.ZERO.compareTo(tottax) != 0) {
                // First try to find the WriteOff posting record
                FactLine[] factlines = fact.getLines();
                boolean foundflwriteoff = false;
                for (int ifl = 0; ifl < factlines.length; ifl++) {
                    FactLine fl = factlines[ifl];
                    if (fl.getAccount().equals(doc.getAccount(Doc.ACCTTYPE_WriteOff, as))) {
                        foundflwriteoff = true;
                        // old balance = DB - CR
                        BigDecimal balamt = fl.getAmtSourceDr().subtract(fl.getAmtSourceCr());
                        // new balance = old balance +/- tottax
                        BigDecimal newbalamt = Env.ZERO;
                        if (invoice.isSOTrx())
                            newbalamt = balamt.subtract(tottax);
                        else
                            newbalamt = balamt.add(tottax);
                        if (Env.ZERO.compareTo(newbalamt) == 0) {
                            // both zeros, remove the line
                            fact.remove(fl);
                        } else if (Env.ZERO.compareTo(newbalamt) > 0) {
                            fl.setAmtAcct(fl.getC_Currency_ID(), Env.ZERO, newbalamt);
                            fl.setAmtSource(fl.getC_Currency_ID(), Env.ZERO, newbalamt);
                        } else {
                            fl.setAmtAcct(fl.getC_Currency_ID(), newbalamt, Env.ZERO);
                            fl.setAmtSource(fl.getC_Currency_ID(), newbalamt, Env.ZERO);
                        }
                        break;
                    }
                }
                if (!foundflwriteoff) {
                    // Create a new line
                    DocLine line = new DocLine(alloc_line, doc);
                    FactLine fl = null;
                    if (invoice.isSOTrx()) {
                        fl = fact.createLine(line, doc.getAccount(Doc.ACCTTYPE_WriteOff, as), as.getC_Currency_ID(), null, tottax);
                    } else {
                        fl = fact.createLine(line, doc.getAccount(Doc.ACCTTYPE_WriteOff, as), as.getC_Currency_ID(), tottax, null);
                    }
                    if (fl != null)
                        fl.setAD_Org_ID(ah.getAD_Org_ID());
                }
            }
        }
    }
    return null;
}
Also used : DocLine(org.compiere.acct.DocLine) FactLine(org.compiere.acct.FactLine) DocTax(org.compiere.acct.DocTax) MInvoice(org.compiere.model.MInvoice) PreparedStatement(java.sql.PreparedStatement) Fact(org.compiere.acct.Fact) BigDecimal(java.math.BigDecimal) SQLException(java.sql.SQLException) MAcctSchema(org.compiere.model.MAcctSchema) ResultSet(java.sql.ResultSet) Doc(org.compiere.acct.Doc) MAllocationLine(org.compiere.model.MAllocationLine)

Example 3 with Doc

use of org.compiere.acct.Doc in project adempiere by adempiere.

the class ClientAcctProcessor method postSession.

//	doIt
/**
	 * 	Post Session
	 */
private void postSession() {
    List<BigDecimal> listProcessedOn = new ArrayList<BigDecimal>();
    for (Timestamp dateacct : getListDateAcct()) {
        listProcessedOn.clear();
        // to include potential null values
        listProcessedOn.add(Env.ZERO);
        //get current time from db
        Timestamp ts = DB.getSQLValueTS(get_TrxName(), "SELECT CURRENT_TIMESTAMP FROM DUAL");
        //go back 2 second to be safe (to avoid posting documents being completed at this precise moment)
        long ms = ts.getTime() - (2 * 1000);
        ts = new Timestamp(ms);
        long mili = ts.getTime();
        BigDecimal value = new BigDecimal(Long.toString(mili));
        //first pass, collect all ts (FR 2962094 - required for weighted average costing)
        int[] documentsTableID = Doc.getDocumentsTableID();
        String[] documentsTableName = Doc.getDocumentsTableName();
        for (int i = 0; i < documentsTableID.length; i++) {
            int AD_Table_ID = documentsTableID[i];
            String TableName = documentsTableName[i];
            //	Post only special documents
            if (p_AD_Table_ID != 0 && p_AD_Table_ID != AD_Table_ID)
                continue;
            StringBuffer sql = new StringBuffer("SELECT DISTINCT ProcessedOn FROM ").append(TableName).append(" WHERE AD_Client_ID=? AND ProcessedOn<?").append(" AND Processed='Y' AND Posted='N' AND IsActive='Y' and " + getColumnNameDateAcct(AD_Table_ID) + "  = ? ");
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
                pstmt.setInt(1, getAD_Client_ID());
                pstmt.setBigDecimal(2, value);
                pstmt.setTimestamp(3, dateacct);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    BigDecimal processedOn = rs.getBigDecimal(1);
                    if (!listProcessedOn.contains(processedOn))
                        listProcessedOn.add(processedOn);
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, sql.toString(), e);
            } finally {
                DB.close(rs, pstmt);
            }
        }
        // initialize counters per table
        int[] count = new int[documentsTableID.length];
        int[] countError = new int[documentsTableID.length];
        for (int i = 0; i < count.length; i++) {
            count[i] = 0;
            countError[i] = 0;
        }
        //sort and post in the processed date order
        Collections.sort(listProcessedOn);
        for (BigDecimal processedOn : listProcessedOn) {
            for (int i = 0; i < documentsTableID.length; i++) {
                int AD_Table_ID = documentsTableID[i];
                String TableName = documentsTableName[i];
                //	Post only special documents
                if (p_AD_Table_ID != 0 && p_AD_Table_ID != AD_Table_ID)
                    continue;
                //  SELECT * FROM table
                StringBuffer sql = new StringBuffer("SELECT * FROM ").append(TableName).append(" WHERE AD_Client_ID=? AND (ProcessedOn");
                if (processedOn.compareTo(Env.ZERO) != 0)
                    sql.append("=?");
                else
                    sql.append(" IS NULL OR ProcessedOn=0");
                sql.append(") AND Processed='Y' AND Posted='N' AND IsActive='Y'").append(" ORDER BY Created");
                //
                PreparedStatement pstmt = null;
                ResultSet rs = null;
                try {
                    pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
                    pstmt.setInt(1, getAD_Client_ID());
                    if (processedOn.compareTo(Env.ZERO) != 0)
                        pstmt.setBigDecimal(2, processedOn);
                    rs = pstmt.executeQuery();
                    while (rs.next()) {
                        count[i]++;
                        boolean ok = true;
                        // Run every posting document in own transaction
                        String innerTrxName = Trx.createTrxName("CAP");
                        Trx innerTrx = Trx.get(innerTrxName, true);
                        String postStatus = Doc.STATUS_NotPosted;
                        Doc doc = Doc.get(m_ass, AD_Table_ID, rs, innerTrxName);
                        try {
                            if (doc == null) {
                                log.severe(getName() + ": No Doc for " + TableName);
                                ok = false;
                            } else {
                                //  post no force/repost
                                String error = doc.post(false, false);
                                ok = (error == null);
                                postStatus = doc.getPostStatus();
                            }
                        } catch (Exception e) {
                            log.log(Level.SEVERE, getName() + ": " + TableName, e);
                            ok = false;
                        } finally {
                            if (ok)
                                innerTrx.commit();
                            else {
                                innerTrx.rollback();
                                // save the posted status error (out of trx)
                                StringBuffer sqlupd = new StringBuffer("UPDATE ").append(doc.get_TableName()).append(" SET Posted='").append(postStatus).append("',Processing='N' ").append("WHERE ").append(doc.get_TableName()).append("_ID=").append(doc.get_ID());
                                DB.executeUpdateEx(sqlupd.toString(), null);
                            }
                            innerTrx.close();
                            innerTrx = null;
                        }
                        if (!ok)
                            countError[i]++;
                    }
                } catch (Exception e) {
                    log.log(Level.SEVERE, sql.toString(), e);
                } finally {
                    DB.close(rs, pstmt);
                }
            }
        // for tableID
        }
        for (int i = 0; i < documentsTableID.length; i++) {
            String TableName = documentsTableName[i];
            if (count[i] > 0) {
                m_summary.append(TableName).append("=").append(count[i]);
                if (countError[i] > 0)
                    m_summary.append("(Errors=").append(countError[i]).append(")");
                m_summary.append(" - ");
                log.finer(getName() + ": " + m_summary.toString());
            } else
                log.finer(getName() + ": " + TableName + " - no work");
        }
    }
}
Also used : ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) ResultSet(java.sql.ResultSet) Doc(org.compiere.acct.Doc) Trx(org.compiere.util.Trx)

Example 4 with Doc

use of org.compiere.acct.Doc in project lar_361 by comitsrl.

the class LAR_Validator method accountingForWithholdingOnPayment.

// voidWarehouseOrder
/**
 * Process acounting for withholding on sales payment
 */
private String accountingForWithholdingOnPayment(final MAllocationHdr ah) {
    final Doc doc = ah.getDoc();
    final List<Fact> facts = doc.getFacts();
    // One fact per acctschema
    for (int i = 0; i < facts.size(); i++) {
        Fact fact = facts.get(i);
        MAcctSchema as = fact.getAcctSchema();
        MAllocationLine[] allocLines = ah.getLines(false);
        for (int j = 0; j < allocLines.length; j++) {
            MAllocationLine al = allocLines[j];
            // TODO is this line necesary?
            doc.setC_BPartner_ID(al.getC_BPartner_ID());
            int c_Payment_ID = al.getC_Payment_ID();
            if (c_Payment_ID <= 0)
                continue;
            MPayment payment = new MPayment(ah.getCtx(), c_Payment_ID, ah.get_TrxName());
            if (payment == null || payment.getC_Payment_ID() == 0)
                continue;
            // Se determina si se procesan cobros o pagos
            if (payment.isReceipt()) {
                // ////////////////  PROCESA COBROS  //////////////////
                // Determine if is an withholding or not
                int c_TaxWithholding_ID = payment.get_ValueAsInt("C_TaxWithholding_ID");
                if (c_TaxWithholding_ID <= 0)
                    continue;
                if (payment.getWriteOffAmt().compareTo(Env.ZERO) <= 0)
                    continue;
                // Iterates over factlines, searching one with writeoff account
                // in order to change it to the retrieved from processed payment
                final FactLine[] factlines = fact.getLines();
                for (int ifl = 0; ifl < factlines.length; ifl++) {
                    final FactLine fl = factlines[ifl];
                    // if factline account is WriteOff, change it
                    if (fl.getAccount().equals(doc.getAccount(Doc.ACCTTYPE_WriteOff, as))) {
                        // Creates factline with proper account (using c_taxwithholding_id from processed payment)
                        final BigDecimal withholdingAmt = payment.getWriteOffAmt();
                        final MTax tw = new MTax(ah.getCtx(), c_TaxWithholding_ID, ah.get_TrxName());
                        final DocTax taxLine = new DocTax(c_TaxWithholding_ID, tw.getName(), tw.getRate(), Env.ZERO, withholdingAmt, tw.isSalesTax());
                        final FactLine newFactLine = fact.createLine(null, taxLine.getAccount(DocTax.ACCTTYPE_TaxCredit, as), as.getC_Currency_ID(), withholdingAmt, null);
                        if (newFactLine != null)
                            newFactLine.setC_Tax_ID(c_TaxWithholding_ID);
                        // Removes factline with writeoff account from fact
                        log.info(String.format("Replace factline: %s -> %s", fl, newFactLine));
                        fact.remove(fl);
                    }
                }
            }
        }
    }
    return null;
}
Also used : FactLine(org.compiere.acct.FactLine) DocTax(org.compiere.acct.DocTax) Fact(org.compiere.acct.Fact) BigDecimal(java.math.BigDecimal) MAcctSchema(org.compiere.model.MAcctSchema) MPayment(org.compiere.model.MPayment) Doc(org.compiere.acct.Doc) MAllocationLine(org.compiere.model.MAllocationLine) MTax(org.compiere.model.MTax)

Aggregations

BigDecimal (java.math.BigDecimal)4 Doc (org.compiere.acct.Doc)4 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 Timestamp (java.sql.Timestamp)2 ArrayList (java.util.ArrayList)2 DocTax (org.compiere.acct.DocTax)2 Fact (org.compiere.acct.Fact)2 FactLine (org.compiere.acct.FactLine)2 MAcctSchema (org.compiere.model.MAcctSchema)2 MAllocationLine (org.compiere.model.MAllocationLine)2 SQLException (java.sql.SQLException)1 DocLine (org.compiere.acct.DocLine)1 MInvoice (org.compiere.model.MInvoice)1 MPayment (org.compiere.model.MPayment)1 MTax (org.compiere.model.MTax)1 Trx (org.compiere.util.Trx)1