Search in sources :

Example 1 with MCostType

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

the class Doc_Invoice method landedCost.

//	createFactCash
/**
	 * 	Create Landed Cost accounting & Cost lines
	 *	@param as accounting schema
	 *	@param fact fact
	 *	@param line document line
	 *	@param isDebit DR entry (normal api)
	 *	@return true if landed costs were created
	 */
private boolean landedCost(MAcctSchema as, Fact fact, DocLine line, boolean isDebit) {
    int invoiceLineId = line.get_ID();
    MLandedCostAllocation[] landedCostAllocations = MLandedCostAllocation.getOfInvoiceLine(getCtx(), invoiceLineId, getTrxName());
    if (landedCostAllocations.length == 0)
        return false;
    BigDecimal totalBase = Arrays.stream(landedCostAllocations).map(MLandedCostAllocation::getBase).reduce(BigDecimal.ZERO, BigDecimal::add);
    //	Create New
    MInvoiceLine invoiceLine = new MInvoiceLine(getCtx(), invoiceLineId, getTrxName());
    Arrays.stream(landedCostAllocations).filter(// only cost allocation with base > 0
    landedCostAllocation -> landedCostAllocation.getBase().signum() != 0).forEach(landedCostAllocation -> {
        BigDecimal percent = landedCostAllocation.getBase().divide(totalBase, BigDecimal.ROUND_HALF_UP);
        String desc = invoiceLine.getDescription();
        if (desc == null)
            desc = percent + "%";
        else
            desc += " - " + percent + "%";
        if (line.getDescription() != null)
            desc += " - " + line.getDescription();
        ProductCost productCost = new ProductCost(Env.getCtx(), landedCostAllocation.getM_Product_ID(), landedCostAllocation.getM_AttributeSetInstance_ID(), getTrxName());
        BigDecimal debitAmount = BigDecimal.ZERO;
        BigDecimal creditAmount = BigDecimal.ZERO;
        ;
        FactLine factLine = null;
        MCostType costType = MCostType.get(as, landedCostAllocation.getM_Product_ID(), landedCostAllocation.getAD_Org_ID());
        if (MCostType.COSTINGMETHOD_AverageInvoice.equals(costType.getCostingMethod())) {
            BigDecimal assetAmount = Optional.ofNullable(MCostDetail.getByDocLineLandedCost(landedCostAllocation, as.getC_AcctSchema_ID(), costType.get_ID())).orElse(BigDecimal.ZERO);
            BigDecimal costAdjustment = landedCostAllocation.getAmt().subtract(assetAmount);
            if (assetAmount.signum() != 0) {
                if (isDebit)
                    debitAmount = assetAmount;
                else
                    creditAmount = assetAmount;
                factLine = fact.createLine(line, productCost.getAccount(ProductCost.ACCTTYPE_P_Asset, as), as.getC_Currency_ID(), debitAmount, creditAmount);
                factLine.setDescription(desc + " " + landedCostAllocation.getM_CostElement().getName());
                factLine.setM_Product_ID(landedCostAllocation.getM_Product_ID());
            }
            if (costAdjustment.signum() != 0) {
                if (isDebit)
                    debitAmount = costAdjustment;
                else
                    creditAmount = costAdjustment;
                factLine = fact.createLine(line, productCost.getAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as), getC_Currency_ID(), debitAmount, creditAmount);
            }
        } else {
            factLine = fact.createLine(line, productCost.getAccount(ProductCost.ACCTTYPE_P_CostAdjustment, as), getC_Currency_ID(), debitAmount, creditAmount);
        }
        factLine.setDescription(desc + " " + landedCostAllocation.getM_CostElement().getName());
        factLine.setM_Product_ID(landedCostAllocation.getM_Product_ID());
    });
    log.config("Created #" + landedCostAllocations.length);
    return true;
}
Also used : Arrays(java.util.Arrays) Env(org.compiere.util.Env) MClientInfo(org.compiere.model.MClientInfo) PreparedStatement(java.sql.PreparedStatement) MCostType(org.compiere.model.MCostType) MLandedCostAllocation(org.compiere.model.MLandedCostAllocation) MAcctSchema(org.compiere.model.MAcctSchema) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ProductCost(org.compiere.model.ProductCost) BigDecimal(java.math.BigDecimal) MInvoice(org.compiere.model.MInvoice) SQLException(java.sql.SQLException) MCurrency(org.compiere.model.MCurrency) DB(org.compiere.util.DB) MInvoiceLine(org.compiere.model.MInvoiceLine) ResultSet(java.sql.ResultSet) MTax(org.compiere.model.MTax) Optional(java.util.Optional) MAccount(org.compiere.model.MAccount) MCostDetail(org.compiere.model.MCostDetail) MLandedCostAllocation(org.compiere.model.MLandedCostAllocation) ProductCost(org.compiere.model.ProductCost) MInvoiceLine(org.compiere.model.MInvoiceLine) MCostType(org.compiere.model.MCostType) BigDecimal(java.math.BigDecimal)

Example 2 with MCostType

use of org.compiere.model.MCostType 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)

Example 3 with MCostType

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

the class Doc_MatchPO method createFacts.

//  getBalance
/**
	 *  Create Facts (the accounting logic) for
	 *  MXP.
	 *  <pre>
	 *      Product PPV     <difference>
	 *      PPV_Offset                  <difference>
	 *  </pre>
	 *  @param as accounting schema
	 *  @return Fact
	 */
public ArrayList<Fact> createFacts(MAcctSchema as) {
    ArrayList<Fact> facts = new ArrayList<Fact>();
    //
    if (//  Nothing to do if no Product
    getM_Product_ID() == 0 || getQty().signum() == 0 || //  No posting if not matched to Shipment
    m_M_InOutLine_ID == 0) {
        log.fine("No Product/Qty - M_Product_ID=" + getM_Product_ID() + ",Qty=" + getQty());
        return facts;
    }
    //  create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    setC_Currency_ID(as.getC_Currency_ID());
    boolean isInterOrg = isInterOrg(as);
    //	Purchase Order Line
    BigDecimal poCost = m_oLine.getPriceCost();
    if (poCost == null || poCost.signum() == 0)
        poCost = m_oLine.getPriceActual();
    MInOutLine receiptLine = new MInOutLine(getCtx(), m_M_InOutLine_ID, getTrxName());
    MInOut inOut = receiptLine.getParent();
    boolean isReturnTrx = inOut.getMovementType().equals(X_M_InOut.MOVEMENTTYPE_VendorReturns);
    // calculate po cost
    //	Delivered so far
    poCost = poCost.multiply(getQty());
    //	Different currency
    if (m_oLine.getC_Currency_ID() != as.getC_Currency_ID()) {
        MOrder order = m_oLine.getParent();
        Timestamp dateAcct = order.getDateAcct();
        BigDecimal rate = MConversionRate.getRate(order.getC_Currency_ID(), as.getC_Currency_ID(), dateAcct, order.getC_ConversionType_ID(), m_oLine.getAD_Client_ID(), m_oLine.getAD_Org_ID());
        if (rate == null) {
            p_Error = "Purchase Order not convertible - " + as.getName();
            return null;
        }
        poCost = poCost.multiply(rate);
        if (poCost.scale() > as.getCostingPrecision())
            poCost = poCost.setScale(as.getCostingPrecision(), BigDecimal.ROUND_HALF_UP);
    }
    //	Calculate PPV for standard costing
    //get standard cost and also make sure cost for other costing method is updated
    MProduct product = MProduct.get(getCtx(), getM_Product_ID());
    MCostType ct = MCostType.get(as, getM_Product_ID(), getAD_Org_ID());
    String costingMethod = ct.getCostingMethod();
    MInOutLine ioLine = new MInOutLine(getCtx(), m_M_InOutLine_ID, getTrxName());
    BigDecimal costs = Env.ZERO;
    for (MTransaction transaction : MTransaction.getByInOutLine(ioLine)) {
        MCostElement element = MCostElement.getByMaterialCostElementType(transaction);
        MCostDetail cd = MCostDetail.getByTransaction(ioLine, transaction, as.getC_AcctSchema_ID(), ct.getM_CostType_ID(), element.getM_CostElement_ID());
        if (cd != null)
            costs = costs.add(MCostDetail.getTotalCost(cd, as));
    }
    if (MCostType.COSTINGMETHOD_StandardCosting.equals(costingMethod)) {
        //	No Costs yet - no PPV
        if (costs == null || costs.signum() == 0) {
            // TODO make these a translatable message
            p_Error = "No Standard Cost information was found for " + product.getName() + ".  Please add a standard cost for material and repost this document.";
            log.log(Level.SEVERE, p_Error);
            return null;
        }
        //	Difference
        BigDecimal difference = poCost.subtract(costs.setScale(as.getCostingPrecision(), BigDecimal.ROUND_HALF_UP));
        //	Nothing to post
        if (difference.signum() == 0) {
            log.log(Level.FINE, "No Cost Difference for M_Product_ID=" + getM_Product_ID());
            return facts;
        }
        //  Product PPV
        FactLine cr = fact.createLine(null, m_pc.getAccount(ProductCost.ACCTTYPE_P_PPV, as), as.getC_Currency_ID(), isReturnTrx ? difference.negate() : difference);
        if (cr != null) {
            cr.setQty(isReturnTrx ? getQty().negate() : getQty());
            cr.setC_BPartner_ID(m_oLine.getC_BPartner_ID());
            cr.setC_Activity_ID(m_oLine.getC_Activity_ID());
            cr.setC_Campaign_ID(m_oLine.getC_Campaign_ID());
            cr.setC_Project_ID(m_oLine.getC_Project_ID());
            cr.setC_ProjectPhase_ID(m_oLine.getC_ProjectPhase_ID());
            cr.setC_ProjectTask_ID(m_oLine.getC_ProjectTask_ID());
            cr.setC_UOM_ID(m_oLine.getC_UOM_ID());
            cr.setUser1_ID(m_oLine.getUser1_ID());
            cr.setUser2_ID(m_oLine.getUser2_ID());
            cr.setUser3_ID(m_oLine.getUser3_ID());
            cr.setUser4_ID(m_oLine.getUser4_ID());
        }
        //  PPV Offset
        FactLine dr = fact.createLine(null, getAccount(Doc.ACCTTYPE_PPVOffset, as), as.getC_Currency_ID(), isReturnTrx ? difference : difference.negate());
        if (dr != null) {
            dr.setQty(isReturnTrx ? getQty() : getQty().negate());
            dr.setC_BPartner_ID(m_oLine.getC_BPartner_ID());
            dr.setC_Activity_ID(m_oLine.getC_Activity_ID());
            dr.setC_Campaign_ID(m_oLine.getC_Campaign_ID());
            dr.setC_Project_ID(m_oLine.getC_Project_ID());
            dr.setC_ProjectPhase_ID(m_oLine.getC_ProjectPhase_ID());
            dr.setC_ProjectTask_ID(m_oLine.getC_ProjectTask_ID());
            dr.setC_UOM_ID(m_oLine.getC_UOM_ID());
            dr.setUser1_ID(m_oLine.getUser1_ID());
            dr.setUser2_ID(m_oLine.getUser2_ID());
            dr.setUser3_ID(m_oLine.getUser3_ID());
            dr.setUser4_ID(m_oLine.getUser4_ID());
        }
        // Avoid usage of clearing accounts
        // If both accounts Purchase Price Variance and Purchase Price Variance Offset are equal
        // then remove the posting
        // PPV
        MAccount acct_db = dr.getAccount();
        // PPV Offset
        MAccount acct_cr = cr.getAccount();
        if ((!as.isPostIfClearingEqual()) && acct_db.equals(acct_cr) && (!isInterOrg)) {
            BigDecimal debit = dr.getAmtSourceDr();
            BigDecimal credit = cr.getAmtSourceCr();
            if (debit.compareTo(credit) == 0) {
                fact.remove(dr);
                fact.remove(cr);
            }
        }
        // End Avoid usage of clearing accounts
        //
        facts.add(fact);
        return facts;
    } else {
        return facts;
    }
}
Also used : MInOut(org.compiere.model.MInOut) MCostElement(org.compiere.model.MCostElement) MProduct(org.compiere.model.MProduct) MInOutLine(org.compiere.model.MInOutLine) MAccount(org.compiere.model.MAccount) ArrayList(java.util.ArrayList) MTransaction(org.compiere.model.MTransaction) MCostType(org.compiere.model.MCostType) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) MOrder(org.compiere.model.MOrder) MCostDetail(org.compiere.model.MCostDetail)

Example 4 with MCostType

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

the class GenerateCostDetail method generateCostDetail.

public void generateCostDetail() {
    //Generate Costdetail
    KeyNamePair[] transactions = getTransactionIdsByDateAcct();
    // System.out.println("Transaction to process : " + transactions.length);
    Integer process = 0;
    Integer productId = 0;
    boolean processNewProduct = true;
    Trx dbTransaction = null;
    try {
        //Process transaction
        for (KeyNamePair keyNamePair : transactions) {
            int transactionId = keyNamePair.getKey();
            int transactionProductId = new Integer(keyNamePair.getName());
            //Detected a new product
            if (productId != transactionProductId) {
                //commit last transaction by product
                if (dbTransaction != null) {
                    dbTransaction.commit(true);
                    dbTransaction.close();
                }
                productId = transactionProductId;
                processNewProduct = true;
                //Create new transaction for this product
                dbTransaction = Trx.get(productId.toString(), true);
            }
            MTransaction transaction = new MTransaction(getCtx(), transactionId, dbTransaction.getTrxName());
            // for each Account Schema
            for (MAcctSchema accountSchema : acctSchemas) {
                // for each Cost Type
                for (MCostType costType : costTypes) {
                    // for each Cost Element
                    for (MCostElement costElement : costElements) {
                        if (processNewProduct) {
                            applyCriteria(accountSchema.getC_AcctSchema_ID(), costType.getM_CostType_ID(), costElement.getM_CostElement_ID(), productId, getAccountDate(), getAccountDateTo());
                            deleteCostDetail(dbTransaction.getTrxName());
                            resetCostDimension(costType.getCostingMethod(), dbTransaction.getTrxName());
                            generateCostCollectorNotTransaction(accountSchema, costType, productId, dbTransaction.getTrxName());
                            processNewProduct = false;
                        }
                        generateCostDetail(accountSchema, costType, costElement, transaction);
                    }
                }
            }
            process++;
        //System.out.println("Transaction : " + transactionId + " Transaction Type :"+ transaction.getMovementType() + " record ..." + process);
        }
        if (dbTransaction != null) {
            dbTransaction.commit(true);
            dbTransaction.close();
            dbTransaction = null;
        }
    } catch (Exception e) {
        if (dbTransaction != null) {
            dbTransaction.rollback();
            dbTransaction.close();
            dbTransaction = null;
            e.printStackTrace();
            addLog(e.getMessage());
        }
    } finally {
        if (dbTransaction != null) {
            dbTransaction.commit();
            dbTransaction.close();
            dbTransaction = null;
        }
    }
}
Also used : MCostElement(org.compiere.model.MCostElement) MAcctSchema(org.compiere.model.MAcctSchema) MTransaction(org.compiere.model.MTransaction) KeyNamePair(org.compiere.util.KeyNamePair) Trx(org.compiere.util.Trx) MCostType(org.compiere.model.MCostType) SQLException(java.sql.SQLException)

Example 5 with MCostType

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

the class FifoLifoCostingMethod method updateCurrentCost.

public void updateCurrentCost(MCostDetail m_costdetail) {
    MCostQueue[] cQueue = MCostQueue.getQueue(dimension, m_costdetail.getDateAcct(), m_costdetail.get_TrxName());
    //TODO: need evaluate this!
    if (cQueue != null) {
        MCostType ct = (MCostType) dimension.getM_CostType();
        if (cQueue.length > 0 && ct.isFifo())
            dimension.setCurrentCostPrice(cQueue[0].getCurrentCostPrice());
        else if (cQueue.length > 0 && MCostElement.COSTELEMENTTYPE_LandedCost.equals(dimension.getM_CostElement().getCostElementType()))
            dimension.setCurrentCostPrice(cQueue[0].getCurrentCostPrice());
    }
    dimension.setCurrentQty(dimension.getCurrentQty().add(m_costdetail.getQty()));
    if (cQueue != null && cQueue.length > 0) {
        BigDecimal cAmt = cQueue[0].getCurrentCostPrice().multiply(m_costdetail.getQty());
        dimension.setCumulatedAmt(dimension.getCumulatedAmt().add(cAmt));
        dimension.setCumulatedQty(dimension.getCumulatedQty().add(m_costdetail.getQty()));
    }
    log.finer("QtyAdjust - FiFo/Lifo - " + dimension);
    dimension.saveEx();
}
Also used : MCostQueue(org.compiere.model.MCostQueue) MCostType(org.compiere.model.MCostType) BigDecimal(java.math.BigDecimal)

Aggregations

MCostType (org.compiere.model.MCostType)20 MCostElement (org.compiere.model.MCostElement)15 MAcctSchema (org.compiere.model.MAcctSchema)13 ArrayList (java.util.ArrayList)11 BigDecimal (java.math.BigDecimal)10 List (java.util.List)8 MProduct (org.compiere.model.MProduct)8 Arrays (java.util.Arrays)7 MCost (org.compiere.model.MCost)7 Query (org.compiere.model.Query)7 Trx (org.compiere.util.Trx)7 MTransaction (org.compiere.model.MTransaction)6 CostDimension (org.adempiere.engine.CostDimension)5 MAccount (org.compiere.model.MAccount)4 MInOutLine (org.compiere.model.MInOutLine)4 Env (org.compiere.util.Env)4 Msg (org.compiere.util.Msg)4 Optional (java.util.Optional)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 AdempiereException (org.adempiere.exceptions.AdempiereException)3