Search in sources :

Example 11 with MAccount

use of org.compiere.model.MAccount in project adempiere by adempiere.

the class DocLine method getAccount.

//  getAccount
/**
	 *  Line Account from Product (or Charge).
	 *
	 *  @param  AcctType see ProductCost.ACCTTYPE_* (0..3)
	 *  @param as Accounting schema
	 *  @return Requested Product Account
	 */
public MAccount getAccount(int AcctType, MAcctSchema as) {
    //	Charge Account
    if (getM_Product_ID() == 0 && getC_Charge_ID() != 0) {
        //	Revenue (-)
        BigDecimal amt = new BigDecimal(-1);
        if (!m_doc.isSOTrx())
            //	Expense (+)
            amt = new BigDecimal(+1);
        MAccount acct = getChargeAccount(as, amt);
        if (acct != null)
            return acct;
    }
    //	Product Account
    return getProductCost().getAccount(AcctType, as, getAD_Org_ID());
}
Also used : MAccount(org.compiere.model.MAccount) BigDecimal(java.math.BigDecimal)

Example 12 with MAccount

use of org.compiere.model.MAccount in project adempiere by adempiere.

the class Doc_AllocationTax method createFacts.

//  getBalance
/**
	 *  Create Facts (the accounting logic) for
	 *  CMA.
	 *  <pre>
	 *  AR_Invoice_Payment
	 *      UnAllocatedCash DR
	 *      or C_Prepayment
	 *      DiscountExp     DR
	 *      WriteOff        DR
	 *      Receivables             CR
	 *  AR_Invoice_Cash
	 *      CashTransfer    DR
	 *      DiscountExp     DR
	 *      WriteOff        DR
	 *      Receivables             CR
	 * 
	 *  AP_Invoice_Payment
	 *      Liability       DR
	 *      DiscountRev             CR
	 *      WriteOff                CR
	 *      PaymentSelect           CR
	 *      or V_Prepayment
	 *  AP_Invoice_Cash
	 *      Liability       DR
	 *      DiscountRev             CR
	 *      WriteOff                CR
	 *      CashTransfer            CR
	 *  CashBankTransfer
	 *      -
	 *  ==============================
	 *  Realized Gain & Loss
	 * 		AR/AP			DR		CR
	 * 		Realized G/L	DR		CR
	 * 
	 *
	 *  </pre>
	 *  Tax needs to be corrected for discount & write-off;
	 *  Currency gain & loss is realized here.
	 *  @param as accounting schema
	 *  @return Fact
	 */
public ArrayList<Fact> createFacts(MAcctSchema as) {
    m_facts = new ArrayList<Fact>();
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    // dummy fact (not posted) to calculate Realized Gain & Loss
    Fact factForRGL = new Fact(this, as, Fact.POST_Actual);
    boolean isInterOrg = isInterOrg(as);
    for (int i = 0; i < p_lines.length; i++) {
        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 && 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()).add(line.getWriteOffAmt());
        // for realized gain & loss purposes
        BigDecimal allocationSourceForRGL = allocationSource;
        // AR/AP balance corrected
        BigDecimal allocationAccounted = Env.ZERO;
        // for realized gain & loss purposes
        BigDecimal allocationAccountedForRGL = Env.ZERO;
        FactLine fl = null;
        FactLine flForRGL = null;
        //	Liability/Receivables
        MAccount bpAcct = null;
        //
        MPayment payment = null;
        if (line.getC_Payment_ID() != 0)
            payment = new MPayment(getCtx(), line.getC_Payment_ID(), getTrxName());
        MInvoice invoice = null;
        if (line.getC_Invoice_ID() != 0)
            invoice = new MInvoice(getCtx(), line.getC_Invoice_ID(), getTrxName());
        //	No Invoice
        if (invoice == null) {
            /**
				   * Adaxa: Paul
				   * Allocate to charges
				   */
            if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() == 0 && line.getC_Charge_ID() != 0) {
                fl = fact.createLine(line, line.getChargeAccount(as, line.getAmtSource()), getC_Currency_ID(), line.getAmtSource());
            } else //	Payment Only
            if (line.getC_Invoice_ID() == 0 && line.getC_Payment_ID() != 0) {
                if (line.getAmtSource().signum() >= 0)
                    fl = fact.createLine(line, getPaymentAcct(as, line.getC_Payment_ID()), getC_Currency_ID(), line.getAmtSource(), null);
                else
                    fl = fact.createLine(line, getPaymentAcct(as, line.getC_Payment_ID()), getC_Currency_ID(), null, line.getAmtSource().negate());
                if (fl != null && payment != null)
                    fl.setAD_Org_ID(payment.getAD_Org_ID());
            } else {
                p_Error = "Cannot determine SO/PO";
                log.log(Level.SEVERE, p_Error);
                return null;
            }
        } else //	Sales Invoice	
        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());
            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 {
                //	Payment/Cash	DR
                if (line.getC_Payment_ID() != 0) {
                    fl = fact.createLine(line, getPaymentAcct(as, line.getC_Payment_ID()), getC_Currency_ID(), line.getAmtSource(), null);
                    if (fl != null && payment != null)
                        fl.setAD_Org_ID(payment.getAD_Org_ID());
                } else if (line.getC_CashLine_ID() != 0) {
                    fl = fact.createLine(line, getCashAcct(as, line.getC_CashLine_ID()), getC_Currency_ID(), line.getAmtSource(), null);
                    MCashLine cashLine = new MCashLine(getCtx(), line.getC_CashLine_ID(), getTrxName());
                    if (fl != null && cashLine.get_ID() != 0)
                        fl.setAD_Org_ID(cashLine.getAD_Org_ID());
                }
            }
            //	Discount		DR
            if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) {
                fl = fact.createLine(line, getAccount(Doc.ACCTTYPE_DiscountExp, as), getC_Currency_ID(), line.getDiscountAmt(), null);
                if (fl != null && payment != null)
                    fl.setAD_Org_ID(payment.getAD_Org_ID());
            }
            //	Write off		DR
            if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) {
                fl = fact.createLine(line, getAccount(Doc.ACCTTYPE_WriteOff, as), getC_Currency_ID(), line.getWriteOffAmt(), null);
                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);
                if (allocationSource.signum() >= 0)
                    //	payment currency
                    fl = fact.createLine(line, bpAcct, getC_Currency_ID(), null, allocationSource);
                else
                    //	payment currency
                    fl = fact.createLine(line, bpAcct, getC_Currency_ID(), allocationSource.negate(), null);
                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, //	payment currency 
                allocationSourceForRGL);
                if (flForRGL != null)
                    allocationAccountedForRGL = flForRGL.getAcctBalance().negate();
            } else //	Cash Based
            {
                allocationAccounted = createCashBasedAcct(as, fact, invoice, allocationSource);
                allocationAccountedForRGL = allocationAccounted;
            }
        } else //	Purchase Invoice
        {
            // Avoid usage of clearing accounts
            // If both accounts Payment Select and Liability are equal
            // then don't post
            MAccount acct_payment_select = null;
            if (line.getC_Payment_ID() != 0)
                acct_payment_select = getPaymentAcct(as, line.getC_Payment_ID());
            else if (line.getC_CashLine_ID() != 0)
                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());
                isUsingClearing = false;
            }
            // End Avoid usage of clearing accounts
            //	allocation is negative
            allocationSource = allocationSource.negate();
            //	AP Invoice Amount	DR
            if (as.isAccrual()) {
                bpAcct = getAccount(Doc.ACCTTYPE_V_Liability, as);
                if (allocationSource.signum() >= 0)
                    //	payment currency
                    fl = fact.createLine(line, bpAcct, getC_Currency_ID(), allocationSource, null);
                else
                    //	payment currency
                    fl = fact.createLine(line, bpAcct, getC_Currency_ID(), null, allocationSource.negate());
                if (fl != null)
                    allocationAccounted = fl.getAcctBalance();
                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(), allocationSourceForRGL, //	payment currency
                null);
                if (flForRGL != null)
                    allocationAccountedForRGL = flForRGL.getAcctBalance();
            } else //	Cash Based
            {
                allocationAccounted = createCashBasedAcct(as, fact, invoice, allocationSource);
                allocationAccountedForRGL = allocationAccounted;
            }
            //	Discount		CR
            if (Env.ZERO.compareTo(line.getDiscountAmt()) != 0) {
                fl = fact.createLine(line, getAccount(Doc.ACCTTYPE_DiscountRev, as), getC_Currency_ID(), null, line.getDiscountAmt().negate());
                if (fl != null && payment != null)
                    fl.setAD_Org_ID(payment.getAD_Org_ID());
            }
            //	Write off		CR
            if (Env.ZERO.compareTo(line.getWriteOffAmt()) != 0) {
                fl = fact.createLine(line, getAccount(Doc.ACCTTYPE_WriteOff, as), getC_Currency_ID(), null, line.getWriteOffAmt().negate());
                if (fl != null && payment != null)
                    fl.setAD_Org_ID(payment.getAD_Org_ID());
            }
            //	Payment/Cash	CR
            if (// Avoid usage of clearing accounts
            isUsingClearing && line.getC_Payment_ID() != 0) {
                fl = fact.createLine(line, getPaymentAcct(as, line.getC_Payment_ID()), getC_Currency_ID(), null, line.getAmtSource().negate());
                if (fl != null && payment != null)
                    fl.setAD_Org_ID(payment.getAD_Org_ID());
            } else if (// Avoid usage of clearing accounts
            isUsingClearing && line.getC_CashLine_ID() != 0) {
                fl = fact.createLine(line, getCashAcct(as, line.getC_CashLine_ID()), getC_Currency_ID(), null, line.getAmtSource().negate());
                MCashLine cashLine = new MCashLine(getCtx(), line.getC_CashLine_ID(), getTrxName());
                if (fl != null && cashLine.get_ID() != 0)
                    fl.setAD_Org_ID(cashLine.getAD_Org_ID());
            }
        }
        //	VAT Tax Correction
        if (invoice != null && as.isTaxCorrection()) {
            BigDecimal taxCorrectionAmt = Env.ZERO;
            if (as.isTaxCorrectionDiscount())
                taxCorrectionAmt = line.getDiscountAmt();
            if (as.isTaxCorrectionWriteOff())
                taxCorrectionAmt = taxCorrectionAmt.add(line.getWriteOffAmt());
            //
            if (taxCorrectionAmt.signum() != 0) {
                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";
                    return null;
                }
            }
        }
        //	Realized Gain & Loss
        if (invoice != null && (//	payment allocation in foreign currency
        getC_Currency_ID() != as.getC_Currency_ID() || //	allocation <> invoice currency
        getC_Currency_ID() != line.getInvoiceC_Currency_ID())) {
            p_Error = createRealizedGainLoss(line, as, fact, bpAcct, invoice, allocationSource, allocationAccounted);
            if (p_Error != null)
                return null;
        }
    }
    // FR [ 1840016 ] Avoid usage of clearing accounts - subject to C_AcctSchema.IsPostIfClearingEqual
    if ((!as.isPostIfClearingEqual()) && p_lines.length > 0 && (!isInterOrg)) {
        boolean allEquals = true;
        // more than one line (i.e. crossing one payment+ with a payment-, or an invoice against a credit memo)
        // verify if the sum of all facts is zero net
        FactLine[] factlines = fact.getLines();
        BigDecimal netBalance = Env.ZERO;
        FactLine prevFactLine = null;
        for (FactLine factLine : factlines) {
            netBalance = netBalance.add(factLine.getAmtSourceDr()).subtract(factLine.getAmtSourceCr());
            if (prevFactLine != null) {
                if (!equalFactLineIDs(prevFactLine, factLine)) {
                    allEquals = false;
                    break;
                }
            }
            prevFactLine = factLine;
        }
        if (netBalance.compareTo(Env.ZERO) == 0 && allEquals) {
            // delete the postings
            for (FactLine factline : factlines) fact.remove(factline);
        }
    }
    //	reset line info
    setC_BPartner_ID(0);
    //
    m_facts.add(fact);
    return m_facts;
}
Also used : MAccount(org.compiere.model.MAccount) MPayment(org.compiere.model.MPayment) MInvoice(org.compiere.model.MInvoice) BigDecimal(java.math.BigDecimal) MCashLine(org.compiere.model.MCashLine)

Example 13 with MAccount

use of org.compiere.model.MAccount in project adempiere by adempiere.

the class Doc_InOut method createFacts.

//  getBalance
/**
	 *  Create Facts (the accounting logic) for
	 *  MMS, MMR.
	 *  <pre>
	 *  Shipment
	 *      CoGS (RevOrg)   DR
	 *      Inventory               CR
	 *  Shipment of Project Issue
	 *      CoGS            DR
	 *      Project                 CR
	 *  Receipt
	 *      Inventory       DR
	 *      NotInvoicedReceipt      CR
	 *  </pre>
	 *  @param as accounting schema
	 *  @return Fact
	 */
public ArrayList<Fact> createFacts(MAcctSchema as) {
    //
    ArrayList<Fact> facts = new ArrayList<Fact>();
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    setC_Currency_ID(as.getC_Currency_ID());
    //  Line pointers
    FactLine dr = null;
    FactLine cr = null;
    //  *** Sales - Shipment
    if (getDocumentType().equals(DOCTYPE_MatShipment) && isSOTrx()) {
        BigDecimal total = Env.ZERO;
        for (int i = 0; i < p_lines.length; i++) {
            DocLine line = p_lines[i];
            BigDecimal costs = null;
            MProduct product = line.getProduct();
            for (MCostDetail cost : line.getCostDetail(as, false)) {
                if (!MCostDetail.existsCost(cost))
                    continue;
                costs = MCostDetail.getTotalCost(cost, as);
                total = total.add(costs);
                //get costing method for product
                String description = cost.getM_CostElement().getName() + " " + cost.getM_CostType().getName();
                //  CoGS            DR
                dr = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Cogs, as), as.getC_Currency_ID(), costs, null);
                if (dr == null) {
                    p_Error = "FactLine DR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                dr.setM_Locator_ID(line.getM_Locator_ID());
                //  from Loc
                dr.setLocationFromLocator(line.getM_Locator_ID(), true);
                //  to Loc
                dr.setLocationFromBPartner(getC_BPartner_Location_ID(), false);
                //	Revenue X-Org
                dr.setAD_Org_ID(line.getOrder_Org_ID());
                dr.setM_Product_ID(cost.getM_Product_ID());
                dr.setQty(cost.getQty().negate());
                dr.addDescription(description);
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctDr from Original Shipment/Receipt
                    if (!dr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty().negate(), Env.ONE.negate())) {
                        p_Error = "Original Shipment/Receipt not posted yet";
                        return null;
                    }
                }
                //  Inventory               CR
                cr = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Asset, as), as.getC_Currency_ID(), null, costs);
                if (cr == null) {
                    p_Error = "FactLine CR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                cr.setM_Locator_ID(line.getM_Locator_ID());
                // from Loc
                cr.setLocationFromLocator(line.getM_Locator_ID(), true);
                // to Loc
                cr.setLocationFromBPartner(getC_BPartner_Location_ID(), false);
                cr.addDescription(description);
                cr.setM_Product_ID(cost.getM_Product_ID());
                cr.setQty(cost.getQty());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctCr from Original Shipment/Receipt
                    if (!cr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty(), Env.ONE.negate())) {
                        p_Error = "Original Shipment/Receipt not posted yet";
                        return null;
                    }
                    //get original cost
                    costs = cr.getAcctBalance();
                }
            }
            // costing elements
            if (//	zero costs OK
            total == null || total.signum() == 0) {
            /*if (product.isStocked())
					{
						p_Error = "No Costs for " + line.getProduct().getName();
						log.log(Level.WARNING, p_Error);
						return null;
					}
					else	//	ignore service
						continue;
					*/
            }
        }
        /** Commitment release										****/
        if (as.isAccrual() && as.isCreateSOCommitment()) {
            for (int i = 0; i < p_lines.length; i++) {
                DocLine line = p_lines[i];
                BigDecimal multiplier = Env.ONE.negate();
                if (m_Reversal_ID != 0 && m_Reversal_ID < get_ID())
                    multiplier = multiplier.negate();
                Fact factcomm = Doc_Order.getCommitmentSalesRelease(as, this, line.getQty(), line.get_ID(), multiplier);
                if (factcomm != null)
                    facts.add(factcomm);
            }
        }
    //	Commitment
    } else //	  *** Sales - Return
    if (getDocumentType().equals(DOCTYPE_MatReceipt) && isSOTrx()) {
        BigDecimal total = Env.ZERO;
        for (int i = 0; i < p_lines.length; i++) {
            DocLine line = p_lines[i];
            BigDecimal costs = null;
            MProduct product = line.getProduct();
            for (MCostDetail cost : line.getCostDetail(as, false)) {
                if (!MCostDetail.existsCost(cost))
                    continue;
                costs = MCostDetail.getTotalCost(cost, as);
                total = total.add(costs);
                String description = cost.getM_CostElement().getName() + " " + cost.getM_CostType().getName();
                //  Inventory               DR
                dr = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Asset, as), as.getC_Currency_ID(), costs, null);
                if (dr == null) {
                    p_Error = "FactLine DR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                dr.setM_Locator_ID(line.getM_Locator_ID());
                // from Loc
                dr.setLocationFromLocator(line.getM_Locator_ID(), true);
                // to Loc
                dr.setLocationFromBPartner(getC_BPartner_Location_ID(), false);
                dr.addDescription(description);
                dr.setM_Product_ID(cost.getM_Product_ID());
                dr.setQty(cost.getQty());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctDr from Original Shipment/Receipt
                    if (!dr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty(), Env.ONE.negate())) {
                        p_Error = "Original Shipment/Receipt not posted yet";
                        return null;
                    }
                    //get original cost
                    costs = dr.getAcctBalance();
                }
                //  CoGS            CR
                cr = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Cogs, as), as.getC_Currency_ID(), null, costs);
                if (cr == null) {
                    p_Error = "FactLine CR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                cr.setM_Locator_ID(line.getM_Locator_ID());
                //  from Loc
                cr.setLocationFromLocator(line.getM_Locator_ID(), true);
                //  to Loc
                cr.setLocationFromBPartner(getC_BPartner_Location_ID(), false);
                //	Revenue X-Org
                cr.setAD_Org_ID(line.getOrder_Org_ID());
                cr.setM_Product_ID(cost.getM_Product_ID());
                cr.setQty(cost.getQty().negate());
                cr.addDescription(description);
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctCr from Original Shipment/Receipt
                    if (!cr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty().negate(), Env.ONE.negate())) {
                        p_Error = "Original Shipment/Receipt not posted yet";
                        return null;
                    }
                }
            }
            if (//	zero costs OK
            total == null || total.signum() == 0) {
            /*if (product.isStocked())
					{
						p_Error = "No Costs for " + line.getProduct().getName();
						log.log(Level.WARNING, p_Error);
						return null;
					}
					else	//	ignore service
						continue;
					*/
            }
        }
    //	for all lines
    } else //  *** Purchasing - Receipt
    if (getDocumentType().equals(DOCTYPE_MatReceipt) && !isSOTrx()) {
        BigDecimal total = Env.ZERO;
        for (int i = 0; i < p_lines.length; i++) {
            int C_Currency_ID = as.getC_Currency_ID();
            //
            DocLine line = p_lines[i];
            BigDecimal costs = null;
            MProduct product = line.getProduct();
            for (MCostDetail cost : line.getCostDetail(as, true)) {
                if (!MCostDetail.existsCost(cost))
                    continue;
                costs = MCostDetail.getTotalCost(cost, as);
                total = total.add(costs);
                String description = cost.getM_CostElement().getName() + " " + cost.getM_CostType().getName();
                //  Inventory/Asset			DR
                MAccount assets = line.getAccount(ProductCost.ACCTTYPE_P_Asset, as);
                if (product.isService()) {
                    //if the line is a Outside Processing then DR WIP
                    if (line.getPP_Cost_Collector_ID() > 0)
                        assets = line.getAccount(ProductCost.ACCTTYPE_P_WorkInProcess, as);
                    else
                        assets = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as);
                }
                dr = fact.createLine(line, assets, C_Currency_ID, costs, null);
                dr.addDescription(description);
                //
                if (dr == null) {
                    p_Error = "DR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                dr.setM_Locator_ID(line.getM_Locator_ID());
                // from Loc
                dr.setLocationFromBPartner(getC_BPartner_Location_ID(), true);
                // to Loc
                dr.setLocationFromLocator(line.getM_Locator_ID(), false);
                dr.setM_Product_ID(cost.getM_Product_ID());
                dr.setQty(cost.getQty());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctDr from Original Shipment/Receipt
                    if (!dr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty(), Env.ONE.negate())) {
                        p_Error = "Original Receipt not posted yet";
                        return null;
                    }
                }
                cr = fact.createLine(line, getAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as), C_Currency_ID, null, costs);
                cr.addDescription(description);
                //
                if (cr == null) {
                    p_Error = "CR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                cr.setM_Locator_ID(line.getM_Locator_ID());
                //  from Loc
                cr.setLocationFromBPartner(getC_BPartner_Location_ID(), true);
                //  to Loc
                cr.setLocationFromLocator(line.getM_Locator_ID(), false);
                cr.setM_Product_ID(cost.getM_Product_ID());
                cr.setQty(cost.getQty().negate());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctCr from Original Shipment/Receipt
                    if (!cr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty().negate(), Env.ONE.negate())) {
                        p_Error = "Original Receipt not posted yet";
                        return null;
                    }
                }
                cost.setProcessed(true);
                cost.saveEx();
            }
        /*if (total == null || total.signum() == 0)
					{
						p_Error = "Resubmit - No Costs for " + product.getName();
						log.log(Level.WARNING, p_Error);
						return null;
					}*/
        }
    } else //	  *** Purchasing - return
    if (getDocumentType().equals(DOCTYPE_MatShipment) && !isSOTrx()) {
        BigDecimal total = Env.ZERO;
        for (int i = 0; i < p_lines.length; i++) {
            int C_Currency_ID = as.getC_Currency_ID();
            //
            DocLine line = p_lines[i];
            BigDecimal costs = null;
            MProduct product = line.getProduct();
            for (MCostDetail cost : line.getCostDetail(as, true)) {
                if (!MCostDetail.existsCost(cost))
                    continue;
                costs = MCostDetail.getTotalCost(cost, as);
                total = total.add(costs);
                String description = cost.getM_CostElement().getName() + " " + cost.getM_CostType().getName();
                dr = fact.createLine(line, getAccount(Doc.ACCTTYPE_NotInvoicedReceipts, as), C_Currency_ID, costs, null);
                dr.addDescription(description);
                //
                if (dr == null) {
                    p_Error = "CR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                dr.setM_Locator_ID(line.getM_Locator_ID());
                //  from Loc
                dr.setLocationFromBPartner(getC_BPartner_Location_ID(), true);
                //  to Loc
                dr.setLocationFromLocator(line.getM_Locator_ID(), false);
                dr.setM_Product_ID(cost.getM_Product_ID());
                dr.setQty(cost.getQty().negate());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctDr from Original Shipment/Receipt
                    if (!dr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty().negate(), Env.ONE.negate())) {
                        p_Error = "Original Receipt not posted yet";
                        return null;
                    }
                }
                //  Inventory/Asset			CR
                MAccount assets = line.getAccount(ProductCost.ACCTTYPE_P_Asset, as);
                if (product.isService())
                    assets = line.getAccount(ProductCost.ACCTTYPE_P_Expense, as);
                cr = fact.createLine(line, assets, C_Currency_ID, null, costs);
                //
                if (cr == null) {
                    p_Error = "DR not created: " + line;
                    log.log(Level.WARNING, p_Error);
                    return null;
                }
                cr.setM_Locator_ID(line.getM_Locator_ID());
                // from Loc
                cr.setLocationFromBPartner(getC_BPartner_Location_ID(), true);
                // to Loc
                cr.setLocationFromLocator(line.getM_Locator_ID(), false);
                cr.addDescription(description);
                cr.setM_Product_ID(cost.getM_Product_ID());
                cr.setQty(cost.getQty());
                if (m_DocStatus.equals(MInOut.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                    //	Set AmtAcctCr from Original Shipment/Receipt
                    if (!cr.updateReverseLine(MInOut.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty(), Env.ONE.negate())) {
                        p_Error = "Original Receipt not posted yet";
                        return null;
                    }
                }
            }
        /*if (total == null || total.signum() == 0)
				{
					p_Error = "Resubmit - No Costs for " + product.getName();
					log.log(Level.WARNING, p_Error);
					return null;
				}*/
        }
    } else //	Purchasing Return
    {
        p_Error = "DocumentType unknown: " + getDocumentType();
        log.log(Level.SEVERE, p_Error);
        return null;
    }
    //
    facts.add(fact);
    return facts;
}
Also used : MProduct(org.compiere.model.MProduct) MAccount(org.compiere.model.MAccount) ArrayList(java.util.ArrayList) MCostDetail(org.compiere.model.MCostDetail) BigDecimal(java.math.BigDecimal)

Example 14 with MAccount

use of org.compiere.model.MAccount in project adempiere by adempiere.

the class Doc_Inventory method createFacts.

//  getBalance
/**
	 *  Create Facts (the accounting logic) for
	 *  MMI.
	 *  <pre>
	 *  Inventory
	 *      Inventory       DR      CR
	 *      InventoryDiff   DR      CR   (or Charge)
	 *  </pre>
	 *  @param as account schema
	 *  @return Fact
	 */
public ArrayList<Fact> createFacts(MAcctSchema as) {
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    setC_Currency_ID(as.getC_Currency_ID());
    //  Line pointers
    FactLine dr = null;
    FactLine cr = null;
    BigDecimal total = Env.ZERO;
    for (int i = 0; i < p_lines.length; i++) {
        DocLine line = p_lines[i];
        BigDecimal costs = Env.ZERO;
        for (MCostDetail cost : line.getCostDetail(as, false)) {
            if (!MCostDetail.existsCost(cost))
                continue;
            //get costing method for product
            String description = cost.getM_CostElement().getName() + " " + cost.getM_CostType().getName();
            if (line.getQty().signum() < 0)
                costs = MCostDetail.getTotalCost(cost, as).negate();
            else
                costs = MCostDetail.getTotalCost(cost, as);
            total = total.add(costs);
            //  Inventory       DR      CR
            dr = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Asset, as), as.getC_Currency_ID(), costs);
            //  may be zero difference - no line created.
            if (dr == null)
                continue;
            dr.setM_Locator_ID(line.getM_Locator_ID());
            dr.addDescription(description);
            dr.setM_Product_ID(cost.getM_Product_ID());
            dr.setQty(cost.getQty());
            if (m_DocStatus.equals(MInventory.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                //	Set AmtAcctDr from Original Phys.Inventory
                if (!dr.updateReverseLine(MInventory.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty(), Env.ONE.negate())) {
                    p_Error = "Original Physical Inventory not posted yet";
                    return null;
                }
            }
            //  InventoryDiff   DR      CR
            //	or Charge
            MAccount invDiff = null;
            if (m_DocStatus.equals(MInventory.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0 && line.getC_Charge_ID() != 0) {
                invDiff = line.getChargeAccount(as, costs);
            } else {
                invDiff = line.getChargeAccount(as, costs.negate());
            }
            if (invDiff == null)
                invDiff = getAccount(Doc.ACCTTYPE_InvDifferences, as);
            cr = fact.createLine(line, invDiff, as.getC_Currency_ID(), costs.negate());
            if (cr == null)
                continue;
            cr.setM_Locator_ID(line.getM_Locator_ID());
            cr.setM_Product_ID(cost.getM_Product_ID());
            cr.setQty(cost.getQty().negate());
            if (//	explicit overwrite for charge
            line.getC_Charge_ID() != 0)
                cr.setAD_Org_ID(line.getAD_Org_ID());
            if (m_DocStatus.equals(MInventory.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                //	Set AmtAcctCr from Original Phys.Inventory
                if (!cr.updateReverseLine(MInventory.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), cost.getQty().negate(), Env.ONE.negate())) {
                    p_Error = "Original Physical Inventory not posted yet";
                    return null;
                }
                //get original cost
                costs = cr.getAcctBalance();
            }
        /*if (total == null || total.signum() == 0)
				{
					p_Error = "No Costs for " + line.getProduct().getName();
					return null;
				}*/
        }
    }
    //
    ArrayList<Fact> facts = new ArrayList<Fact>();
    facts.add(fact);
    return facts;
}
Also used : MAccount(org.compiere.model.MAccount) ArrayList(java.util.ArrayList) MCostDetail(org.compiere.model.MCostDetail) BigDecimal(java.math.BigDecimal)

Example 15 with MAccount

use of org.compiere.model.MAccount in project adempiere by adempiere.

the class Doc_Production method createFacts.

//  getBalance
/**
	 *  Create Facts (the accounting logic) for
	 *  MMP.
	 *  <pre>
	 *  Production
	 *      Inventory       DR      CR
	 *  </pre>
	 *  @param as account schema
	 *  @return Fact
	 */
public ArrayList<Fact> createFacts(MAcctSchema as) {
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    setC_Currency_ID(as.getC_Currency_ID());
    //  Line pointer
    FactLine factLine = null;
    BigDecimal total = Env.ZERO;
    DocLine parentProductionLine = null;
    for (DocLine line : p_lines) {
        MProduct product = line.getProduct();
        if (line.isProductionBOM())
            parentProductionLine = line;
        if (X_M_Product.PRODUCTTYPE_Item.equals(product.getProductType())) {
            BigDecimal totalCosts = Env.ZERO;
            BigDecimal qty = line.getQty();
            BigDecimal costTransaction = Env.ZERO;
            for (MCostDetail cost : line.getCostDetail(as, false)) {
                if (!MCostDetail.existsCost(cost))
                    continue;
                costTransaction = MCostDetail.getTotalCost(cost, as);
                totalCosts = totalCosts.add(costTransaction);
            }
            if (qty.signum() < 0)
                totalCosts = totalCosts.negate();
            total = total.add(totalCosts);
            factLine = fact.createLine(line, line.getAccount(ProductCost.ACCTTYPE_P_Asset, as), line.getAccount(ProductCost.ACCTTYPE_P_Asset, as), as.getC_Currency_ID(), totalCosts);
            factLine.setM_Product_ID(line.getM_Product_ID());
            factLine.setM_Locator_ID(line.getM_LocatorTo_ID());
            factLine.setDescription("");
            factLine.saveEx();
        } else if (!X_M_Product.PRODUCTTYPE_Item.equals(product.getProductType())) {
            BigDecimal totalCosts = Env.ZERO;
            MAccount acct = null;
            for (MCostElement costElement : MCostElement.getCostElement(line.getCtx(), line.getTrxName())) {
                if (MCostElement.COSTELEMENTTYPE_BurdenMOverhead.equals(costElement.getCostElementType()))
                    acct = line.getAccount(ProductCost.ACCTTYPE_P_Burden, as);
                else if (MCostElement.COSTELEMENTTYPE_OutsideProcessing.equals(costElement.getCostElementType()))
                    acct = line.getAccount(ProductCost.ACCTTYPE_P_OutsideProcessing, as);
                else if (MCostElement.COSTELEMENTTYPE_Overhead.equals(costElement.getCostElementType()))
                    acct = line.getAccount(ProductCost.ACCTTYPE_P_Overhead, as);
                else if (MCostElement.COSTELEMENTTYPE_Resource.equals(costElement.getCostElementType()))
                    acct = line.getAccount(ProductCost.ACCTTYPE_P_Labor, as);
                else
                    acct = line.getAccount(ProductCost.ACCTTYPE_P_OutsideProcessing, as);
                int warehouseId = DB.getSQLValue(line.getTrxName(), "SELECT M_Warehouse_ID from M_Locator WHERE M_Locator_ID=?", line.getM_Locator_ID());
                BigDecimal costTransaction = Env.ZERO;
                MCost costDimension = MCost.validateCostForCostType(as, (MCostType) as.getM_CostType(), costElement, product.getM_Product_ID(), line.getAD_Org_ID(), warehouseId, line.getM_AttributeSetInstance_ID(), line.getTrxName());
                if (costDimension != null)
                    costTransaction = costDimension.getCurrentCostPrice().add(costDimension.getCurrentCostPriceLL());
                totalCosts = totalCosts.add(costTransaction.multiply(line.getQty()));
            }
            factLine = fact.createLine(line, acct, acct, as.getC_Currency_ID(), totalCosts);
            factLine.setM_Product_ID(line.getM_Product_ID());
            factLine.setM_Locator_ID(line.getM_LocatorTo_ID());
            if (m_DocStatus.equals(MProduction.DOCSTATUS_Reversed) && m_Reversal_ID != 0 && line.getReversalLine_ID() != 0) {
                //	Set AmtAcctDr from Original Phys.Inventory
                if (!factLine.updateReverseLine(MProduction.Table_ID, m_Reversal_ID, line.getReversalLine_ID(), line.getQty(), Env.ONE)) {
                    p_Error = "Original Physical Inventory not posted yet";
                    return null;
                }
            }
            factLine.setDescription("");
            factLine.saveEx();
            total = total.add(totalCosts);
        }
    }
    // When total no is zero then create an adjustment cost , can happen when of resource rate was changes from original cost finish good
    if (total.signum() != 0) {
        factLine = fact.createLine(parentProductionLine, parentProductionLine.getAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as), as.getC_Currency_ID(), total);
        factLine.setM_Product_ID(parentProductionLine.getM_Product_ID());
        factLine.setM_Locator_ID(parentProductionLine.getM_LocatorTo_ID());
        factLine.setDescription(" Adjustment Cost");
        factLine.saveEx();
    }
    ArrayList<Fact> facts = new ArrayList<Fact>();
    facts.add(fact);
    return facts;
}
Also used : MCostElement(org.compiere.model.MCostElement) MProduct(org.compiere.model.MProduct) MAccount(org.compiere.model.MAccount) MCost(org.compiere.model.MCost) ArrayList(java.util.ArrayList) MCostType(org.compiere.model.MCostType) MCostDetail(org.compiere.model.MCostDetail) BigDecimal(java.math.BigDecimal)

Aggregations

MAccount (org.compiere.model.MAccount)42 BigDecimal (java.math.BigDecimal)25 ArrayList (java.util.ArrayList)16 MCostDetail (org.compiere.model.MCostDetail)8 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)7 MProduct (org.compiere.model.MProduct)6 SQLException (java.sql.SQLException)5 MCostElement (org.compiere.model.MCostElement)5 MJournalLine (org.compiere.model.MJournalLine)4 MCostType (org.compiere.model.MCostType)3 Timestamp (java.sql.Timestamp)2 MAcctSchemaElement (org.compiere.model.MAcctSchemaElement)2 MCharge (org.compiere.model.MCharge)2 MElementValue (org.compiere.model.MElementValue)2 MInvoice (org.compiere.model.MInvoice)2 AdempiereSystemError (org.compiere.util.AdempiereSystemError)2 TreeMap (java.util.TreeMap)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 I_C_Project (org.compiere.model.I_C_Project)1