Search in sources :

Example 6 with MAcctSchema

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

the class Doc method get.

//	get
/**
	 *  Create Posting document
	 *	@param ass accounting schema
	 *  @param AD_Table_ID Table ID of Documents
	 *  @param rs ResultSet
	 *  @param trxName transaction name
	 *  @return Document
	 * @throws AdempiereUserError 
	 */
public static Doc get(MAcctSchema[] ass, int AD_Table_ID, ResultSet rs, String trxName) throws AdempiereUserError {
    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;
}
Also used : MAcctSchema(org.compiere.model.MAcctSchema) AdempiereUserError(org.compiere.util.AdempiereUserError) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException)

Example 7 with MAcctSchema

use of org.compiere.model.MAcctSchema 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 8 with MAcctSchema

use of org.compiere.model.MAcctSchema 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 9 with MAcctSchema

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

the class CostUpdate method getCosts.

//	update
/**
	 * 	Get Costs
	 *	@param cost cost
	 *	@param to where to get costs from 
	 *	@return costs (could be 0) or null if not found
	 *	@throws Exception
	 */
private BigDecimal getCosts(MCost cost, String to) throws Exception {
    BigDecimal retValue = null;
    MCostElement costElement = MCostElement.getByMaterialCostElementType(cost);
    if (costElement == null)
        throw new AdempiereSystemError("@M_CostElement_ID@ @NotFound@: ");
    //	Average Invoice
    if (to.equals(TO_AverageInvoice)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_AverageInvoice);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getCurrentCostPrice();
    } else //	Average Invoice History
    if (to.equals(TO_AverageInvoiceHistory)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_AverageInvoice);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getHistoryAverage();
    } else //	Average PO
    if (to.equals(TO_AveragePO)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_AveragePO);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getCurrentCostPrice();
    } else //	Average PO History
    if (to.equals(TO_AveragePOHistory)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_AveragePO);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getHistoryAverage();
    } else //	FiFo
    if (to.equals(TO_FiFo)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_FiFo);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getCurrentCostPrice();
    } else //	Future Std Costs
    if (to.equals(TO_FutureStandardCost))
        retValue = cost.getFutureCostPrice();
    else //	Last Inv Price
    if (to.equals(TO_LastInvoicePrice)) {
        if (costElement != null) {
            MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
            if (costDimension != null)
                retValue = costDimension.getCurrentCostPrice();
        }
        if (retValue == null) {
            MProduct product = MProduct.get(getCtx(), cost.getM_Product_ID());
            MAcctSchema as = MAcctSchema.get(getCtx(), cost.getC_AcctSchema_ID());
            retValue = MCost.getLastInvoicePrice(product, cost.getM_AttributeSetInstance_ID(), cost.getAD_Org_ID(), as.getC_Currency_ID());
        }
    } else //	Last PO Price
    if (to.equals(TO_LastPOPrice)) {
        if (costElement != null) {
            MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
            if (costDimension != null)
                retValue = costDimension.getCurrentCostPrice();
        }
        if (retValue == null) {
            MProduct product = MProduct.get(getCtx(), cost.getM_Product_ID());
            MAcctSchema as = MAcctSchema.get(getCtx(), cost.getC_AcctSchema_ID());
            retValue = MCost.getLastPOPrice(product, cost.getM_AttributeSetInstance_ID(), cost.getAD_Org_ID(), as.getC_Currency_ID());
        }
    } else //	FiFo
    if (to.equals(TO_LiFo)) {
        if (costElement == null)
            throw new AdempiereSystemError("CostElement not found: " + TO_LiFo);
        MCost costDimension = getDimension(cost, costElement.getM_CostElement_ID());
        if (costDimension != null)
            retValue = costDimension.getCurrentCostPrice();
    } else //	Old Std Costs
    if (to.equals(TO_OldStandardCost))
        retValue = getOldCurrentCostPrice(cost);
    else //	Price List
    if (to.equals(TO_PriceListLimit))
        retValue = getPrice(cost);
    else //	Standard Costs
    if (to.equals(TO_StandardCost))
        retValue = cost.getCurrentCostPrice();
    return retValue;
}
Also used : MCostElement(org.compiere.model.MCostElement) MProduct(org.compiere.model.MProduct) MAcctSchema(org.compiere.model.MAcctSchema) AdempiereSystemError(org.compiere.util.AdempiereSystemError) MCost(org.compiere.model.MCost) BigDecimal(java.math.BigDecimal)

Example 10 with MAcctSchema

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

the class BPGroupAcctCopy method doIt.

//	prepare
/**
	 * 	Process
	 *	@return message
	 *	@throws Exception
	 */
protected String doIt() throws Exception {
    log.info("C_AcctSchema_ID=" + p_C_AcctSchema_ID);
    if (p_C_AcctSchema_ID == 0)
        throw new AdempiereSystemError("C_AcctSchema_ID=0");
    MAcctSchema as = MAcctSchema.get(getCtx(), p_C_AcctSchema_ID);
    if (as.get_ID() == 0)
        throw new AdempiereSystemError("Not Found - C_AcctSchema_ID=" + p_C_AcctSchema_ID);
    //
    String sql = null;
    int updated = 0;
    int created = 0;
    int updatedTotal = 0;
    int createdTotal = 0;
    //	Update existing Customers
    sql = "UPDATE C_BP_Customer_Acct ca " + "SET (C_Receivable_Acct,C_Receivable_Services_Acct,C_PrePayment_Acct)=" + " (SELECT C_Receivable_Acct,C_Receivable_Services_Acct,C_PrePayment_Acct " + " FROM C_BP_Group_Acct" + " WHERE C_BP_Group_ID=" + p_C_BP_Group_ID + " AND C_AcctSchema_ID=" + p_C_AcctSchema_ID + "), Updated=SysDate, UpdatedBy=0 " + "WHERE ca.C_AcctSchema_ID=" + p_C_AcctSchema_ID + " AND EXISTS (SELECT * FROM C_BPartner p " + "WHERE p.C_BPartner_ID=ca.C_BPartner_ID" + " AND p.C_BP_Group_ID=" + p_C_BP_Group_ID + ")";
    updated = DB.executeUpdate(sql, get_TrxName());
    addLog(0, null, new BigDecimal(updated), "@Updated@ @C_BPartner_ID@ @IsCustomer@");
    updatedTotal += updated;
    //	Insert new Customer
    sql = "INSERT INTO C_BP_Customer_Acct " + "(C_BPartner_ID, C_AcctSchema_ID," + " AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy," + " C_Receivable_Acct, C_Receivable_Services_Acct, C_PrePayment_Acct) " + "SELECT p.C_BPartner_ID, acct.C_AcctSchema_ID," + " p.AD_Client_ID, p.AD_Org_ID, 'Y', SysDate, 0, SysDate, 0," + " acct.C_Receivable_Acct, acct.C_Receivable_Services_Acct, acct.C_PrePayment_Acct " + "FROM C_BPartner p" + " INNER JOIN C_BP_Group_Acct acct ON (acct.C_BP_Group_ID=p.C_BP_Group_ID)" + "WHERE acct.C_AcctSchema_ID=" + //	#
    p_C_AcctSchema_ID + " AND p.C_BP_Group_ID=" + p_C_BP_Group_ID + " AND NOT EXISTS (SELECT * FROM C_BP_Customer_Acct ca " + "WHERE ca.C_BPartner_ID=p.C_BPartner_ID" + " AND ca.C_AcctSchema_ID=acct.C_AcctSchema_ID)";
    created = DB.executeUpdate(sql, get_TrxName());
    addLog(0, null, new BigDecimal(created), "@Created@ @C_BPartner_ID@ @IsCustomer@");
    createdTotal += created;
    //	Update existing Vendors
    sql = "UPDATE C_BP_Vendor_Acct va " + "SET (V_Liability_Acct,V_Liability_Services_Acct,V_PrePayment_Acct)=" + " (SELECT V_Liability_Acct,V_Liability_Services_Acct,V_PrePayment_Acct " + " FROM C_BP_Group_Acct" + " WHERE C_BP_Group_ID=" + p_C_BP_Group_ID + " AND C_AcctSchema_ID=" + p_C_AcctSchema_ID + "), Updated=SysDate, UpdatedBy=0 " + "WHERE va.C_AcctSchema_ID=" + p_C_AcctSchema_ID + " AND EXISTS (SELECT * FROM C_BPartner p " + "WHERE p.C_BPartner_ID=va.C_BPartner_ID" + " AND p.C_BP_Group_ID=" + p_C_BP_Group_ID + ")";
    updated = DB.executeUpdate(sql, get_TrxName());
    addLog(0, null, new BigDecimal(updated), "@Updated@ @C_BPartner_ID@ @IsVendor@");
    updatedTotal += updated;
    //	Insert new Vendors
    sql = "INSERT INTO C_BP_Vendor_Acct " + "(C_BPartner_ID, C_AcctSchema_ID," + " AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, Updated, UpdatedBy," + " V_Liability_Acct, V_Liability_Services_Acct, V_PrePayment_Acct) " + "SELECT p.C_BPartner_ID, acct.C_AcctSchema_ID," + " p.AD_Client_ID, p.AD_Org_ID, 'Y', SysDate, 0, SysDate, 0," + " acct.V_Liability_Acct, acct.V_Liability_Services_Acct, acct.V_PrePayment_Acct " + "FROM C_BPartner p" + " INNER JOIN C_BP_Group_Acct acct ON (acct.C_BP_Group_ID=p.C_BP_Group_ID)" + "WHERE acct.C_AcctSchema_ID=" + //	#
    p_C_AcctSchema_ID + " AND p.C_BP_Group_ID=" + p_C_BP_Group_ID + " AND NOT EXISTS (SELECT * FROM C_BP_Vendor_Acct va " + "WHERE va.C_BPartner_ID=p.C_BPartner_ID AND va.C_AcctSchema_ID=acct.C_AcctSchema_ID)";
    created = DB.executeUpdate(sql, get_TrxName());
    addLog(0, null, new BigDecimal(created), "@Created@ @C_BPartner_ID@ @IsVendor@");
    createdTotal += created;
    return "@Created@=" + createdTotal + ", @Updated@=" + updatedTotal;
}
Also used : MAcctSchema(org.compiere.model.MAcctSchema) AdempiereSystemError(org.compiere.util.AdempiereSystemError) BigDecimal(java.math.BigDecimal)

Aggregations

MAcctSchema (org.compiere.model.MAcctSchema)45 BigDecimal (java.math.BigDecimal)20 MCostElement (org.compiere.model.MCostElement)18 MProduct (org.compiere.model.MProduct)15 ArrayList (java.util.ArrayList)14 MCostType (org.compiere.model.MCostType)14 List (java.util.List)12 MCost (org.compiere.model.MCost)12 Arrays (java.util.Arrays)11 Query (org.compiere.model.Query)11 Trx (org.compiere.util.Trx)9 AdempiereException (org.adempiere.exceptions.AdempiereException)8 Env (org.compiere.util.Env)8 CostDimension (org.adempiere.engine.CostDimension)7 SQLException (java.sql.SQLException)6 MAcctSchemaElement (org.compiere.model.MAcctSchemaElement)6 Msg (org.compiere.util.Msg)6 Timestamp (java.sql.Timestamp)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 AdempiereSystemError (org.compiere.util.AdempiereSystemError)5