Search in sources :

Example 11 with MBPartner

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

the class ImportBudget method fillIdValues.

/**
     * Fill Id Values
     * @param importBudget
     * @param acctSchemaElements
     * @param trxName
     */
private void fillIdValues(X_I_Budget importBudget, MAcctSchemaElement[] acctSchemaElements, String trxName) {
    StringBuffer stringError = new StringBuffer("");
    // Set Organization
    Integer orgId = 0;
    if (importBudget.getAD_Org_ID() > 0)
        orgId = importBudget.getAD_Org_ID();
    if (orgId <= 0 && importBudget.getOrgValue() != null)
        orgId = getId(MOrg.Table_Name, MOrg.COLUMNNAME_Value + "=?", trxName, importBudget.getOrgValue());
    if (orgId > 0 && importBudget.getAD_Org_ID() <= 0)
        importBudget.setAD_Org_ID(orgId);
    if (importBudget.getAD_Org_ID() <= 0 && importBudget.getOrgValue() != null)
        stringError.append("@AD_Org_ID@ @NotFound@ ");
    // Set Organization Trx
    Integer orgTrxId = 0;
    if (importBudget.getAD_OrgTrx_ID() > 0)
        orgTrxId = importBudget.getAD_OrgTrx_ID();
    if (orgTrxId <= 0 && importBudget.getOrgTrxValue() != null)
        orgTrxId = getId(MOrg.Table_Name, MOrg.COLUMNNAME_Value + "=?", trxName, importBudget.getOrgTrxValue());
    if (orgTrxId > 0 && importBudget.getAD_OrgTrx_ID() <= 0)
        importBudget.setAD_OrgTrx_ID(orgTrxId);
    if (importBudget.getAD_Org_ID() <= 0 && importBudget.getOrgTrxValue() != null)
        stringError.append("@AD_OrgTrx_ID@ @NotFound@ ");
    // Set Account Schema
    Integer accountSchemaId = 0;
    if (importBudget.getC_AcctSchema_ID() > 0)
        accountSchemaId = importBudget.getC_AcctSchema_ID();
    if (accountSchemaId <= 0 && importBudget.getAcctSchemaName() != null)
        accountSchemaId = getId(MAcctSchema.Table_Name, MAcctSchema.COLUMNNAME_Name + "=?", trxName, importBudget.getAcctSchemaName());
    if (accountSchemaId > 0 && importBudget.getC_AcctSchema_ID() <= 0)
        importBudget.setC_AcctSchema_ID(accountSchemaId);
    else {
        accountSchemaId = getAccountingSchemaId();
        importBudget.setC_AcctSchema_ID(accountSchemaId);
    }
    // Set Budget
    Integer budgetId = 0;
    if (importBudget.getGL_Budget_ID() > 0)
        budgetId = importBudget.getGL_Budget_ID();
    if (budgetId <= 0 && importBudget.getBudgetCode() != null)
        budgetId = getId(X_GL_Budget.Table_Name, X_GL_Budget.COLUMNNAME_Name + "=?", trxName, importBudget.getBudgetCode());
    if (budgetId > 0 && importBudget.getGL_Budget_ID() <= 0)
        importBudget.setGL_Budget_ID(budgetId);
    if (importBudget.getGL_Budget_ID() <= 0 && importBudget.getBudgetCode() != null)
        stringError.append("@GL_Budget_ID@ @NotFound@ ");
    // Set Asset
    Integer assetId = 0;
    if (importBudget.getA_Asset_ID() > 0)
        assetId = importBudget.getA_Asset_ID();
    if (assetId <= 0 && importBudget.getAssetValue() != null)
        assetId = getId(X_A_Asset.Table_Name, X_A_Asset.COLUMNNAME_Value + "=?", trxName, importBudget.getAssetValue());
    if (assetId > 0 && importBudget.getA_Asset_ID() <= 0)
        importBudget.setA_Asset_ID(assetId);
    if (importBudget.getA_Asset_ID() <= 0 && importBudget.getAssetValue() != null)
        stringError.append("@A_Asset_ID@ @NotFound@ ");
    // Set Account
    int accountId = 0;
    if (importBudget.getAccount_ID() > 0)
        accountId = importBudget.getAccount_ID();
    if (accountId <= 0 && importBudget.getAccountValue() != null)
        accountId = getId(MElementValue.Table_Name, MElementValue.COLUMNNAME_Value + "=?", trxName, importBudget.getAccountValue());
    if (accountId > 0 && importBudget.getAccount_ID() <= 0)
        importBudget.setAccount_ID(accountId);
    if (importBudget.getAccount_ID() <= 0 && importBudget.getAccountValue() != null)
        stringError.append("@Account_ID@ @NotFound@ ");
    int partnerId = 0;
    if (importBudget.getC_BPartner_ID() > 0)
        partnerId = importBudget.getC_BPartner_ID();
    if (partnerId <= 0 && importBudget.getBPartnerValue() != null) {
        MBPartner partner = MBPartner.get(getCtx(), importBudget.getBPartnerValue());
        if (partner != null)
            partnerId = partner.getC_BPartner_ID();
    }
    if (partnerId > 0 && importBudget.getC_BPartner_ID() <= 0)
        importBudget.setC_BPartner_ID(partnerId);
    if (importBudget.getC_BPartner_ID() <= 0 && importBudget.getBPartnerValue() != null)
        stringError.append("@C_BPartner_ID@ @NotFound@ ");
    // Set Product
    Integer productId = 0;
    if (importBudget.getM_Product_ID() > 0)
        productId = importBudget.getM_Product_ID();
    if (productId <= 0 && importBudget.getProductValue() != null)
        productId = getId(MProduct.Table_Name, MProduct.COLUMNNAME_Value + "=?", trxName, importBudget.getProductValue());
    if (productId > 0 && importBudget.getM_Product_ID() <= 0)
        importBudget.setM_Product_ID(productId);
    if (importBudget.getM_Product_ID() <= 0 && importBudget.getProductValue() != null)
        stringError.append("@M_Product_ID@ @NotFound@ ");
    // Set Project
    Integer projectId = 0;
    if (importBudget.getC_Project_ID() > 0)
        projectId = importBudget.getC_Project_ID();
    if (projectId <= 0 && importBudget.getProjectValue() != null)
        projectId = getId(MProject.Table_Name, MProject.COLUMNNAME_Value + "=?", trxName, importBudget.getProjectValue());
    if (projectId > 0 && importBudget.getC_Project_ID() <= 0)
        importBudget.setC_Project_ID(projectId);
    if (importBudget.getC_Project_ID() <= 0 && importBudget.getProjectValue() != null)
        stringError.append("@C_Project_ID@ @NotFound@ ");
    // Set Campaign
    Integer campaignId = 0;
    if (importBudget.getC_Campaign_ID() > 0)
        campaignId = importBudget.getC_Campaign_ID();
    if (campaignId <= 0 && importBudget.getCampaignValue() != null)
        campaignId = getId(MCampaign.Table_Name, MCampaign.COLUMNNAME_Value + "=?", trxName, importBudget.getCampaignValue());
    if (campaignId > 0 && importBudget.getC_Campaign_ID() <= 0)
        importBudget.setC_Campaign_ID(campaignId);
    if (importBudget.getC_Campaign_ID() <= 0 && importBudget.getCampaignValue() != null)
        stringError.append("@C_Campaign_ID@ @NotFound@ ");
    // Set Sales Region
    Integer salesRegionId = 0;
    if (importBudget.getC_SalesRegion_ID() > 0)
        salesRegionId = importBudget.getC_SalesRegion_ID();
    if (salesRegionId <= 0 && importBudget.getSalesRegionValue() != null)
        salesRegionId = getId(MSalesRegion.Table_Name, MSalesRegion.COLUMNNAME_Value + "=?", trxName, importBudget.getSalesRegionValue());
    if (salesRegionId > 0 && importBudget.getC_SalesRegion_ID() <= 0)
        importBudget.setC_SalesRegion_ID(salesRegionId);
    if (importBudget.getC_SalesRegion_ID() <= 0 && importBudget.getSalesRegionValue() != null)
        stringError.append("@C_SalesRegion_ID@ @NotFound@");
    // Set Activity Id
    Integer activityId = 0;
    if (importBudget.getC_Activity_ID() > 0)
        activityId = importBudget.getC_Activity_ID();
    if (activityId <= 0 && importBudget.getActivityValue() != null)
        activityId = getId(MActivity.Table_Name, MActivity.COLUMNNAME_Value + "=?", trxName, importBudget.getActivityValue());
    if (accountId > 0 && importBudget.getC_Activity_ID() <= 0)
        importBudget.setC_Activity_ID(activityId);
    if (importBudget.getC_Activity_ID() <= 0 && importBudget.getActivityValue() != null)
        stringError.append("@C_SalesRegion_ID@ @NotFound@ ");
    // Set Sub Acct Id
    Integer subAcctountId = 0;
    if (importBudget.getC_SubAcct_ID() > 0)
        subAcctountId = importBudget.getC_SubAcct_ID();
    if (subAcctountId <= 0 && importBudget.getSubAcctValue() != null)
        subAcctountId = getId(X_C_SubAcct.Table_Name, X_C_SubAcct.COLUMNNAME_Value + "=?", trxName, importBudget.getSubAcctValue());
    if (subAcctountId > 0 && importBudget.getC_SubAcct_ID() <= 0)
        importBudget.setC_SubAcct_ID(subAcctountId);
    if (importBudget.getC_SubAcct_ID() <= 0 && importBudget.getSubAcctValue() != null)
        stringError.append("@C_SubAcct_ID@ @NotFound@ ");
    // Set User 1
    Integer user1Id = 0;
    if (importBudget.getUser1_ID() > 0)
        user1Id = importBudget.getUser1_ID();
    if (user1Id <= 0 && importBudget.getUser1_ID() <= 0 && importBudget.getUserValue1() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList1.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser1_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue1()));
        });
    }
    if (importBudget.getUser1_ID() <= 0 && importBudget.getUserValue1() != null)
        stringError.append("@User1_ID@ @NotFound@ ");
    // User 2
    Integer user2Id = 0;
    if (importBudget.getUser2_ID() > 0)
        user2Id = importBudget.getUser2_ID();
    if (user2Id <= 0 && importBudget.getUser2_ID() <= 0 && importBudget.getUserValue2() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList2.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser2_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue2()));
        });
    }
    if (importBudget.getUser2_ID() <= 0 && importBudget.getUserValue2() != null)
        stringError.append("@User2_ID@ @NotFound@ ");
    Integer user3Id = 0;
    if (importBudget.getUser3_ID() > 0)
        user3Id = importBudget.getUser3_ID();
    if (user3Id <= 0 && importBudget.getUser3_ID() <= 0 && importBudget.getUserValue3() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList3.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser3_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue3()));
        });
    }
    if (importBudget.getUser3_ID() <= 0 && importBudget.getUserValue3() != null)
        stringError.append("@User3_ID@ @NotFound@ ");
    Integer user4Id = 0;
    if (importBudget.getUser4_ID() > 0)
        user4Id = importBudget.getUser4_ID();
    if (user4Id <= 0 && importBudget.getUser4_ID() <= 0 && importBudget.getUserValue4() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList4.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser4_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue4()));
        });
    }
    if (importBudget.getUser4_ID() <= 0 && importBudget.getUserValue4() != null)
        stringError.append("@User4_ID@ @NotFound@ ");
    Integer userElement1Id = 0;
    if (importBudget.getUserElement1_ID() > 0)
        userElement1Id = importBudget.getUserElement1_ID();
    if (userElement1Id <= 0 && importBudget.getUserElement1_ID() <= 0 && importBudget.getUserElementValue1() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserElement1.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            I_AD_Column column = acctSchemaElement.getAD_Column();
            MTable table = (MTable) column.getAD_Table();
            MColumn columnName = table.getColumn("Value");
            if (columnName == null)
                columnName = table.getColumn("Name");
            if (columnName != null)
                importBudget.setUserElement1_ID(getId(table.getTableName(), columnName.getColumnName() + "=?", trxName, importBudget.getUserElementValue1()));
        });
    }
    if (importBudget.getUserElement1_ID() <= 0 && importBudget.getUserElementValue1() != null)
        stringError.append("@UserElement1_ID@ @NotFound@ ");
    Integer userElement2Id = 0;
    if (importBudget.getUserElement2_ID() > 0)
        userElement2Id = importBudget.getUserElement2_ID();
    if (userElement2Id <= 0 && importBudget.getUserElement2_ID() <= 0 && importBudget.getUserElementValue2() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserElement2.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            I_AD_Column column = acctSchemaElement.getAD_Column();
            MTable table = (MTable) column.getAD_Table();
            MColumn columnName = table.getColumn("Value");
            if (columnName == null)
                columnName = table.getColumn("Name");
            if (columnName != null)
                importBudget.setUserElement2_ID(getId(table.getTableName(), columnName.getColumnName() + "=?", trxName, importBudget.getUserElementValue2()));
        });
    }
    if (importBudget.getUserElement2_ID() <= 0 && importBudget.getUserElementValue2() != null)
        stringError.append("@UserElement2_ID@ @NotFound@ ");
    if (accountSchemaId <= 0)
        stringError.append("@C_AcctSchema_ID@ @NotFound@ ");
    if (budgetId <= 0)
        stringError.append("@GL_Budget_ID@ @NotFound@ ");
    if (accountId <= 0)
        stringError.append("@Account_ID@ @NotFound@ ");
    if (!stringError.toString().isEmpty() && stringError.toString().length() > 0) {
        importBudget.setI_ErrorMsg(Msg.parseTranslation(getCtx(), stringError.toString()));
        importBudget.saveEx();
    }
    importBudget.saveEx();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MAcctSchemaElement(org.compiere.model.MAcctSchemaElement) Arrays(java.util.Arrays) MProject(org.compiere.model.MProject) X_I_Budget(org.compiere.model.X_I_Budget) CLogger(org.compiere.util.CLogger) MJournalLine(org.compiere.model.MJournalLine) MJournalBatch(org.compiere.model.MJournalBatch) Env(org.compiere.util.Env) SimpleDateFormat(java.text.SimpleDateFormat) X_GL_Budget(org.compiere.model.X_GL_Budget) MCampaign(org.compiere.model.MCampaign) AtomicReference(java.util.concurrent.atomic.AtomicReference) MAcctSchema(org.compiere.model.MAcctSchema) ArrayList(java.util.ArrayList) MActivity(org.compiere.model.MActivity) MSalesRegion(org.compiere.model.MSalesRegion) BigDecimal(java.math.BigDecimal) Query(org.compiere.model.Query) DB(org.compiere.util.DB) Calendar(java.util.Calendar) MBPartner(org.compiere.model.MBPartner) Msg(org.compiere.util.Msg) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MElementValue(org.compiere.model.MElementValue) MPeriod(org.compiere.model.MPeriod) Trx(org.compiere.util.Trx) MJournal(org.compiere.model.MJournal) DateFormat(java.text.DateFormat) Timestamp(java.sql.Timestamp) X_C_SubAcct(org.compiere.model.X_C_SubAcct) Logger(java.util.logging.Logger) MColumn(org.compiere.model.MColumn) Date(java.sql.Date) I_AD_Column(org.compiere.model.I_AD_Column) List(java.util.List) MOrg(org.compiere.model.MOrg) AdempiereException(org.adempiere.exceptions.AdempiereException) X_A_Asset(org.compiere.model.X_A_Asset) MTable(org.compiere.model.MTable) MAccount(org.compiere.model.MAccount) MProduct(org.compiere.model.MProduct) I_I_Budget(org.compiere.model.I_I_Budget) MColumn(org.compiere.model.MColumn) MTable(org.compiere.model.MTable) I_AD_Column(org.compiere.model.I_AD_Column) MBPartner(org.compiere.model.MBPartner)

Example 12 with MBPartner

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

the class DistributionCreate method doIt.

//	prepare
/**
	 *  Perform process.
	 *  @return Message (text with variables)
	 *  @throws Exception if not successful
	 */
protected String doIt() throws Exception {
    log.info("M_DistributionList_ID=" + p_M_DistributionList_ID + ", M_Product_ID=" + p_M_Product_ID + ", Qty=" + p_Qty + ", Test=" + p_IsTest);
    if (p_IsCreateSingleOrder)
        log.info("SingleOrder=" + p_IsCreateSingleOrder + ", BPartner_ID=" + p_Bill_BPartner_ID + ", Location_ID=" + p_Bill_Location_ID);
    //
    if (p_M_DistributionList_ID == 0)
        throw new IllegalArgumentException("No Distribution List ID");
    m_dl = new MDistributionList(getCtx(), p_M_DistributionList_ID, get_TrxName());
    if (m_dl.get_ID() == 0)
        throw new Exception("Distribution List not found -  M_DistributionList_ID=" + p_M_DistributionList_ID);
    //
    if (p_M_Product_ID == 0)
        throw new IllegalArgumentException("No Product");
    m_product = MProduct.get(getCtx(), p_M_Product_ID);
    if (m_product.get_ID() == 0)
        throw new Exception("Product not found -  M_Product_ID=" + p_M_Product_ID);
    if (p_Qty == null || p_Qty.signum() != 1)
        throw new IllegalArgumentException("No Quantity");
    //
    if (p_IsCreateSingleOrder && p_Bill_BPartner_ID == 0)
        throw new IllegalArgumentException("Invoice Business Partner required for single Order");
    //	Create Single Order
    if (!p_IsTest && p_IsCreateSingleOrder) {
        MBPartner bp = new MBPartner(getCtx(), p_Bill_BPartner_ID, get_TrxName());
        if (bp.get_ID() == 0)
            throw new IllegalArgumentException("Single Business Partner not found - C_BPartner_ID=" + p_Bill_BPartner_ID);
        //
        m_singleOrder = new MOrder(getCtx(), 0, get_TrxName());
        m_singleOrder.setIsSOTrx(true);
        m_singleOrder.setC_DocTypeTarget_ID(MOrder.DocSubTypeSO_Standard);
        m_singleOrder.setBPartner(bp);
        if (p_Bill_Location_ID != 0)
            m_singleOrder.setC_BPartner_Location_ID(p_Bill_Location_ID);
        if (!m_singleOrder.save())
            throw new IllegalStateException("Single Order not created");
    }
    MDistributionListLine[] lines = m_dl.getLines();
    int counter = 0;
    for (int i = 0; i < lines.length; i++) {
        if (createOrder(lines[i]))
            counter++;
    }
    //	Update Qty
    if (m_singleOrder != null) {
        m_singleOrder.setDescription("# " + counter + " - " + m_totalQty);
        m_singleOrder.saveEx();
    }
    return "@Created@ #" + counter + " - @Qty@=" + m_totalQty;
}
Also used : MOrder(org.compiere.model.MOrder) MDistributionListLine(org.compiere.model.MDistributionListLine) MDistributionList(org.compiere.model.MDistributionList) MBPartner(org.compiere.model.MBPartner)

Example 13 with MBPartner

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

the class DistributionCreate method createOrder.

//	doIt
/**
	 * 	Create Order for Distribution Line
	 *	@param dll Distribution Line
	 *	@return true if created
	 */
private boolean createOrder(MDistributionListLine dll) {
    MBPartner bp = new MBPartner(getCtx(), dll.getC_BPartner_ID(), get_TrxName());
    if (bp.get_ID() == 0)
        throw new IllegalArgumentException("Business Partner not found - C_BPartner_ID=" + dll.getC_BPartner_ID());
    //	Create Order
    MOrder order = m_singleOrder;
    if (!p_IsTest && order == null) {
        order = new MOrder(getCtx(), 0, get_TrxName());
        order.setIsSOTrx(true);
        order.setC_DocTypeTarget_ID(MOrder.DocSubTypeSO_Standard);
        order.setBPartner(bp);
        if (dll.getC_BPartner_Location_ID() != 0)
            order.setC_BPartner_Location_ID(dll.getC_BPartner_Location_ID());
        if (!order.save()) {
            log.log(Level.SEVERE, "Order not saved");
            return false;
        }
    }
    //	Calculate Qty
    BigDecimal ratio = dll.getRatio();
    BigDecimal qty = p_Qty.multiply(ratio);
    if (qty.compareTo(Env.ZERO) != 0)
        qty = qty.divide(m_dl.getRatioTotal(), m_product.getUOMPrecision(), BigDecimal.ROUND_HALF_UP);
    BigDecimal minQty = dll.getMinQty();
    if (qty.compareTo(minQty) < 0)
        qty = minQty;
    m_totalQty = m_totalQty.add(qty);
    //
    if (p_IsTest) {
        addLog(0, null, qty, bp.getName());
        return false;
    }
    //	Create Order Line
    MOrderLine line = new MOrderLine(order);
    line.setC_BPartner_ID(dll.getC_BPartner_ID());
    if (dll.getC_BPartner_Location_ID() != 0)
        line.setC_BPartner_Location_ID(dll.getC_BPartner_Location_ID());
    //
    line.setM_Product_ID(p_M_Product_ID, true);
    line.setQty(qty);
    line.setPrice();
    if (!line.save()) {
        log.log(Level.SEVERE, "OrderLine not saved");
        return false;
    }
    addLog(0, null, qty, order.getDocumentNo() + ": " + bp.getName());
    return true;
}
Also used : MOrder(org.compiere.model.MOrder) MBPartner(org.compiere.model.MBPartner) MOrderLine(org.compiere.model.MOrderLine) BigDecimal(java.math.BigDecimal)

Example 14 with MBPartner

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

the class DistributionRun method distributionOrders.

//	insertDetails
/**************************************************************************
	 * 	Create Orders
	 * 	@return true if created
	 */
private boolean distributionOrders() {
    //The Quantity Available is distribute with respect to Distribution Order Demand
    if (p_BasedInDamnd) {
        int M_Warehouse_ID = 0;
        if (p_M_Warehouse_ID <= 0) {
            MOrgInfo oi_source = MOrgInfo.get(getCtx(), m_run.getAD_Org_ID(), get_TrxName());
            MWarehouse m_source = MWarehouse.get(getCtx(), oi_source.getM_Warehouse_ID());
            if (m_source == null)
                throw new AdempiereException("Do not exist Defautl Warehouse Source");
            M_Warehouse_ID = m_source.getM_Warehouse_ID();
        } else
            M_Warehouse_ID = p_M_Warehouse_ID;
        //			For all lines
        for (int i = 0; i < m_details.length; i++) {
            MDistributionRunDetail detail = m_details[i];
            StringBuffer sql = new StringBuffer("SELECT * FROM DD_OrderLine ol INNER JOIN DD_Order o ON (o.DD_Order_ID=ol.DD_Order_ID)  INNER JOIN M_Locator l ON (l.M_Locator_ID=ol.M_Locator_ID) ");
            //sql.append(" WHERE o.DocStatus IN ('DR','IN') AND o.C_BPartner_ID = ? AND M_Product_ID=? AND  l.M_Warehouse_ID=?  AND ol.DatePromised BETWEEN ? AND ? ");
            sql.append(" WHERE o.DocStatus IN ('DR','IN') AND o.C_BPartner_ID = ? AND M_Product_ID=? AND  l.M_Warehouse_ID=?  AND ol.DatePromised <=?");
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
                pstmt.setInt(1, detail.getC_BPartner_ID());
                pstmt.setInt(2, detail.getM_Product_ID());
                pstmt.setInt(3, M_Warehouse_ID);
                pstmt.setTimestamp(4, p_DatePromised);
                //pstmt.setTimestamp(5, p_DatePromised_To);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    //	Create Order Line
                    MDDOrderLine line = new MDDOrderLine(getCtx(), rs, get_TrxName());
                    line.setM_Product_ID(detail.getM_Product_ID());
                    line.setConfirmedQty(line.getTargetQty().add(detail.getActualAllocation()));
                    if (p_M_Warehouse_ID > 0)
                        line.setDescription(Msg.translate(getCtx(), "PlannedQty"));
                    else
                        line.setDescription(m_run.getName());
                    line.saveEx();
                    break;
                //addLog(0,null, detail.getActualAllocation(), order.getDocumentNo() 
                //	+ ": " + bp.getName() + " - " + product.getName());
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, "doIt - " + sql, e);
                return false;
            } finally {
                DB.close(rs, pstmt);
                rs = null;
                pstmt = null;
            }
        }
        return true;
    }
    //		Get Counter Org/BP
    int runAD_Org_ID = m_run.getAD_Org_ID();
    if (runAD_Org_ID == 0)
        runAD_Org_ID = Env.getAD_Org_ID(getCtx());
    MOrg runOrg = MOrg.get(getCtx(), runAD_Org_ID);
    int runC_BPartner_ID = runOrg.getLinkedC_BPartner_ID(get_TrxName());
    boolean counter = //	no single Order 
    !m_run.isCreateSingleOrder() && //	Org linked to BP
    runC_BPartner_ID > 0 && //	PO
    !m_docType.isSOTrx();
    MBPartner runBPartner = counter ? new MBPartner(getCtx(), runC_BPartner_ID, get_TrxName()) : null;
    if (!counter || runBPartner == null || runBPartner.get_ID() != runC_BPartner_ID)
        counter = false;
    if (counter)
        log.info("RunBP=" + runBPartner + " - " + m_docType);
    log.info("Single=" + m_run.isCreateSingleOrder() + " - " + m_docType + ",SO=" + m_docType.isSOTrx());
    log.fine("Counter=" + counter + ",C_BPartner_ID=" + runC_BPartner_ID + "," + runBPartner);
    //
    MBPartner bp = null;
    MDDOrder singleOrder = null;
    MProduct product = null;
    MWarehouse m_source = null;
    MLocator m_locator = null;
    MWarehouse m_target = null;
    MLocator m_locator_to = null;
    MWarehouse[] ws = null;
    MOrgInfo oi_source = MOrgInfo.get(getCtx(), m_run.getAD_Org_ID(), get_TrxName());
    m_source = MWarehouse.get(getCtx(), oi_source.getM_Warehouse_ID());
    if (m_source == null)
        throw new AdempiereException("Do not exist Defautl Warehouse Source");
    m_locator = MLocator.getDefault(m_source);
    //get the warehouse in transit
    ws = MWarehouse.getInTransitForOrg(getCtx(), m_source.getAD_Org_ID());
    if (ws == null)
        throw new AdempiereException("Warehouse Intransit do not found");
    //	Consolidated Single Order 
    if (m_run.isCreateSingleOrder()) {
        bp = new MBPartner(getCtx(), m_run.getC_BPartner_ID(), get_TrxName());
        if (bp.get_ID() == 0)
            throw new IllegalArgumentException("Business Partner not found - C_BPartner_ID=" + m_run.getC_BPartner_ID());
        //
        if (!p_IsTest) {
            singleOrder = new MDDOrder(getCtx(), 0, get_TrxName());
            singleOrder.setC_DocType_ID(m_docType.getC_DocType_ID());
            singleOrder.setIsSOTrx(m_docType.isSOTrx());
            singleOrder.setBPartner(bp);
            if (m_run.getC_BPartner_Location_ID() != 0)
                singleOrder.setC_BPartner_Location_ID(m_run.getC_BPartner_Location_ID());
            singleOrder.setDateOrdered(m_DateOrdered);
            singleOrder.setDatePromised(p_DatePromised);
            singleOrder.setM_Warehouse_ID(ws[0].getM_Warehouse_ID());
            if (!singleOrder.save()) {
                log.log(Level.SEVERE, "Order not saved");
                return false;
            }
            m_counter++;
        }
    }
    int lastC_BPartner_ID = 0;
    int lastC_BPartner_Location_ID = 0;
    MDDOrder order = null;
    //	For all lines
    for (int i = 0; i < m_details.length; i++) {
        MDistributionRunDetail detail = m_details[i];
        //	Create Order Header
        if (m_run.isCreateSingleOrder())
            order = singleOrder;
        else //	New Business Partner
        if (lastC_BPartner_ID != detail.getC_BPartner_ID() || lastC_BPartner_Location_ID != detail.getC_BPartner_Location_ID()) {
            //	finish order
            order = null;
        }
        lastC_BPartner_ID = detail.getC_BPartner_ID();
        lastC_BPartner_Location_ID = detail.getC_BPartner_Location_ID();
        bp = new MBPartner(getCtx(), detail.getC_BPartner_ID(), get_TrxName());
        MOrgInfo oi_target = MOrgInfo.get(getCtx(), bp.getAD_OrgBP_ID_Int(), get_TrxName());
        m_target = MWarehouse.get(getCtx(), oi_target.getM_Warehouse_ID());
        if (m_target == null)
            throw new AdempiereException("Do not exist Default Warehouse Target");
        m_locator_to = MLocator.getDefault(m_target);
        if (m_locator == null || m_locator_to == null) {
            throw new AdempiereException("Do not exist default Locator for Warehouses");
        }
        if (p_ConsolidateDocument) {
            String whereClause = "DocStatus IN ('DR','IN') AND AD_Org_ID=" + bp.getAD_OrgBP_ID_Int() + " AND " + MDDOrder.COLUMNNAME_C_BPartner_ID + "=? AND " + MDDOrder.COLUMNNAME_M_Warehouse_ID + "=?  AND " + MDDOrder.COLUMNNAME_DatePromised + "<=? ";
            order = new Query(getCtx(), MDDOrder.Table_Name, whereClause, get_TrxName()).setParameters(new Object[] { lastC_BPartner_ID, ws[0].getM_Warehouse_ID(), p_DatePromised }).setOrderBy(MDDOrder.COLUMNNAME_DatePromised + " DESC").first();
        }
        //	New Order
        if (order == null) {
            if (!p_IsTest) {
                order = new MDDOrder(getCtx(), 0, get_TrxName());
                order.setAD_Org_ID(bp.getAD_OrgBP_ID_Int());
                order.setC_DocType_ID(m_docType.getC_DocType_ID());
                order.setIsSOTrx(m_docType.isSOTrx());
                //	Counter Doc
                if (counter && bp.getAD_OrgBP_ID_Int() > 0) {
                    log.fine("Counter - From_BPOrg=" + bp.getAD_OrgBP_ID_Int() + "-" + bp + ", To_BP=" + runBPartner);
                    order.setAD_Org_ID(bp.getAD_OrgBP_ID_Int());
                    if (ws[0].getM_Warehouse_ID() > 0)
                        order.setM_Warehouse_ID(ws[0].getM_Warehouse_ID());
                    order.setBPartner(runBPartner);
                } else //	normal
                {
                    log.fine("From_Org=" + runAD_Org_ID + ", To_BP=" + bp);
                    order.setAD_Org_ID(bp.getAD_OrgBP_ID_Int());
                    order.setBPartner(bp);
                    if (detail.getC_BPartner_Location_ID() != 0)
                        order.setC_BPartner_Location_ID(detail.getC_BPartner_Location_ID());
                }
                order.setM_Warehouse_ID(ws[0].getM_Warehouse_ID());
                order.setDateOrdered(m_DateOrdered);
                order.setDatePromised(p_DatePromised);
                order.setIsInDispute(false);
                order.setIsInTransit(false);
                if (!order.save()) {
                    log.log(Level.SEVERE, "Order not saved");
                    return false;
                }
            }
        }
        //	Line
        if (product == null || product.getM_Product_ID() != detail.getM_Product_ID())
            product = MProduct.get(getCtx(), detail.getM_Product_ID());
        if (p_IsTest) {
            addLog(0, null, detail.getActualAllocation(), bp.getName() + " - " + product.getName());
            continue;
        }
        if (p_ConsolidateDocument) {
            String sql = "SELECT DD_OrderLine_ID FROM DD_OrderLine ol INNER JOIN DD_Order o ON (o.DD_Order_ID=ol.DD_Order_ID) WHERE o.DocStatus IN ('DR','IN') AND o.C_BPartner_ID = ? AND M_Product_ID=? AND  ol.M_Locator_ID=?  AND ol.DatePromised <= ?";
            int DD_OrderLine_ID = DB.getSQLValueEx(get_TrxName(), sql, new Object[] { detail.getC_BPartner_ID(), product.getM_Product_ID(), m_locator.getM_Locator_ID(), p_DatePromised });
            if (DD_OrderLine_ID <= 0) {
                MDDOrderLine line = new MDDOrderLine(order);
                line.setAD_Org_ID(bp.getAD_OrgBP_ID_Int());
                line.setM_Locator_ID(m_locator.getM_Locator_ID());
                line.setM_LocatorTo_ID(m_locator_to.getM_Locator_ID());
                line.setIsInvoiced(false);
                line.setProduct(product);
                BigDecimal QtyAllocation = detail.getActualAllocation();
                if (QtyAllocation == null)
                    QtyAllocation = Env.ZERO;
                line.setQty(QtyAllocation);
                line.setQtyEntered(QtyAllocation);
                //line.setTargetQty(detail.getActualAllocation());
                line.setTargetQty(Env.ZERO);
                String Description = "";
                if (m_run.getName() != null)
                    Description = Description.concat(m_run.getName());
                line.setDescription(Description + " " + Msg.translate(getCtx(), "Qty") + " = " + QtyAllocation + " ");
                //line.setConfirmedQty(QtyAllocation);
                line.saveEx();
            } else {
                MDDOrderLine line = new MDDOrderLine(getCtx(), DD_OrderLine_ID, get_TrxName());
                BigDecimal QtyAllocation = detail.getActualAllocation();
                if (QtyAllocation == null)
                    QtyAllocation = Env.ZERO;
                String Description = line.getDescription();
                if (Description == null)
                    Description = "";
                if (m_run.getName() != null)
                    Description = Description.concat(m_run.getName());
                line.setDescription(Description + " " + Msg.translate(getCtx(), "Qty") + " = " + QtyAllocation + " ");
                line.setQty(line.getQtyEntered().add(QtyAllocation));
                //line.setConfirmedQty(line.getConfirmedQty().add( QtyAllocation));
                line.saveEx();
            }
        } else {
            //	Create Order Line
            MDDOrderLine line = new MDDOrderLine(order);
            if (counter && bp.getAD_OrgBP_ID_Int() > 0)
                //	don't overwrite counter doc
                ;
            /*else	//	normal - optionally overwrite
				{
					line.setC_BPartner_ID(detail.getC_BPartner_ID());
					if (detail.getC_BPartner_Location_ID() != 0)
						line.setC_BPartner_Location_ID(detail.getC_BPartner_Location_ID());
				}*/
            //
            line.setAD_Org_ID(bp.getAD_OrgBP_ID_Int());
            line.setM_Locator_ID(m_locator.getM_Locator_ID());
            line.setM_LocatorTo_ID(m_locator_to.getM_Locator_ID());
            line.setIsInvoiced(false);
            line.setProduct(product);
            line.setQty(detail.getActualAllocation());
            line.setQtyEntered(detail.getActualAllocation());
            //line.setTargetQty(detail.getActualAllocation());
            line.setTargetQty(Env.ZERO);
            //line.setConfirmedQty(detail.getActualAllocation());
            String Description = "";
            if (m_run.getName() != null)
                Description = Description.concat(m_run.getName());
            line.setDescription(Description + " " + Msg.translate(getCtx(), "Qty") + " = " + detail.getActualAllocation() + " ");
            line.saveEx();
        }
        addLog(0, null, detail.getActualAllocation(), order.getDocumentNo() + ": " + bp.getName() + " - " + product.getName());
    }
    //	finish order
    order = null;
    return true;
}
Also used : MProduct(org.compiere.model.MProduct) Query(org.compiere.model.Query) PreparedStatement(java.sql.PreparedStatement) MBPartner(org.compiere.model.MBPartner) MWarehouse(org.compiere.model.MWarehouse) AdempiereException(org.adempiere.exceptions.AdempiereException) BigDecimal(java.math.BigDecimal) MDistributionRunDetail(org.compiere.model.MDistributionRunDetail) MDDOrderLine(org.eevolution.model.MDDOrderLine) MOrg(org.compiere.model.MOrg) AdempiereException(org.adempiere.exceptions.AdempiereException) MLocator(org.compiere.model.MLocator) MOrgInfo(org.compiere.model.MOrgInfo) ResultSet(java.sql.ResultSet) MDDOrder(org.eevolution.model.MDDOrder)

Example 15 with MBPartner

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

the class ImportBPartner method doIt.

//	prepare
/**
	 *  Perform process.
	 *  @return Message
	 *  @throws Exception
	 */
protected String doIt() throws java.lang.Exception {
    StringBuffer sql = null;
    int no = 0;
    String clientCheck = getWhereClause();
    //	Delete Old Imported
    if (m_deleteOldImported) {
        sql = new StringBuffer("DELETE I_BPartner " + "WHERE I_IsImported='Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Delete Old Impored =" + no);
    }
    //	Set Client, Org, IsActive, Created/Updated
    sql = new StringBuffer("UPDATE I_BPartner " + "SET AD_Client_ID = COALESCE (AD_Client_ID, ").append(m_AD_Client_ID).append(")," + " AD_Org_ID = COALESCE (AD_Org_ID, 0)," + " IsActive = COALESCE (IsActive, 'Y')," + " Created = COALESCE (Created, SysDate)," + " CreatedBy = COALESCE (CreatedBy, 0)," + " Updated = COALESCE (Updated, SysDate)," + " UpdatedBy = COALESCE (UpdatedBy, 0)," + " I_ErrorMsg = ' '," + " I_IsImported = 'N' " + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Reset=" + no);
    ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_BEFORE_VALIDATE);
    //	Set BP_Group
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET GroupValue=(SELECT MAX(Value) FROM C_BP_Group g WHERE g.IsDefault='Y'" + " AND g.AD_Client_ID=i.AD_Client_ID) ");
    sql.append("WHERE GroupValue IS NULL AND C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Group Default=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BP_Group_ID=(SELECT C_BP_Group_ID FROM C_BP_Group g" + " WHERE i.GroupValue=g.Value AND g.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Group=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Group, ' " + "WHERE C_BP_Group_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.config("Invalid Group=" + no);
    //	Set Country
    /**
		sql = new StringBuffer ("UPDATE I_BPartner i "
			+ "SET CountryCode=(SELECT CountryCode FROM C_Country c WHERE c.IsDefault='Y'"
			+ " AND c.AD_Client_ID IN (0, i.AD_Client_ID) AND ROWNUM=1) "
			+ "WHERE CountryCode IS NULL AND C_Country_ID IS NULL"
			+ " AND I_IsImported<>'Y'").append(clientCheck);
		no = DB.executeUpdateEx(sql.toString(), get_TrxName());
		log.fine("Set Country Default=" + no);
		 **/
    //
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_Country_ID=(SELECT C_Country_ID FROM C_Country c" + " WHERE i.CountryCode=c.CountryCode AND c.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Country_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Country=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Country, ' " + "WHERE C_Country_ID IS NULL AND (City IS NOT NULL OR Address1 IS NOT NULL)" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.config("Invalid Country=" + no);
    //	Set Region
    sql = new StringBuffer("UPDATE I_BPartner i " + "Set RegionName=(SELECT MAX(Name) FROM C_Region r" + " WHERE r.IsDefault='Y' AND r.C_Country_ID=i.C_Country_ID" + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) ");
    sql.append("WHERE RegionName IS NULL AND C_Region_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Region Default=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner i " + "Set C_Region_ID=(SELECT C_Region_ID FROM C_Region r" + " WHERE r.Name=i.RegionName AND r.C_Country_ID=i.C_Country_ID" + " AND r.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Region_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Region=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Region, ' " + "WHERE C_Region_ID IS NULL " + " AND EXISTS (SELECT * FROM C_Country c" + " WHERE c.C_Country_ID=i.C_Country_ID AND c.HasRegion='Y')" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.config("Invalid Region=" + no);
    //	Set Greeting
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_Greeting_ID=(SELECT C_Greeting_ID FROM C_Greeting g" + " WHERE i.BPContactGreeting=g.Name AND g.AD_Client_ID IN (0, i.AD_Client_ID)) " + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Greeting=" + no);
    //
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Greeting, ' " + "WHERE C_Greeting_ID IS NULL AND BPContactGreeting IS NOT NULL" + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.config("Invalid Greeting=" + no);
    // Existing User. Lookup by AD_User.Email - BPartner
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BPartner_ID=" + "(SELECT C_BPartner_ID FROM AD_User u " + "WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) " + "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Found EMail User=" + no);
    // Existing User. Lookup by AD_User.Email - AD_User
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET AD_User_ID=" + "(SELECT AD_User_ID FROM AD_User u " + "WHERE i.EMail=u.EMail AND u.AD_Client_ID=i.AD_Client_ID) " + "WHERE i.EMail IS NOT NULL AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Found EMail User=" + no);
    //	Existing BPartner ? Match Value
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p" + " WHERE i.Value=p.Value AND p.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BPartner_ID IS NULL AND Value IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Found BPartner=" + no);
    //	Existing Contact ? Match Name
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET AD_User_ID=(SELECT AD_User_ID FROM AD_User c" + " WHERE i.ContactName=c.Name AND i.C_BPartner_ID=c.C_BPartner_ID AND c.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_BPartner_ID IS NOT NULL AND AD_User_ID IS NULL AND ContactName IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Found Contact=" + no);
    //		Existing Location ? Exact Match
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET C_BPartner_Location_ID=(SELECT C_BPartner_Location_ID" + " FROM C_BPartner_Location bpl INNER JOIN C_Location l ON (bpl.C_Location_ID=l.C_Location_ID)" + " WHERE i.C_BPartner_ID=bpl.C_BPartner_ID AND bpl.AD_Client_ID=i.AD_Client_ID" + " AND (i.Address1=l.Address1 OR (i.Address1 IS NULL AND l.Address1 IS NULL))" + " AND (i.Address2=l.Address2 OR (i.Address2 IS NULL AND l.Address2 IS NULL))" + " AND (i.City=l.City OR (i.City IS NULL AND l.City IS NULL))" + " AND (i.Postal=l.Postal OR (i.Postal IS NULL AND l.Postal IS NULL))" + " AND (i.Postal_Add=l.Postal_Add OR (l.Postal_Add IS NULL AND l.Postal_Add IS NULL))" + " AND i.C_Region_ID=l.C_Region_ID AND i.C_Country_ID=l.C_Country_ID) " + "WHERE C_BPartner_ID IS NOT NULL AND C_BPartner_Location_ID IS NULL" + " AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Found Location=" + no);
    //	Interest Area
    sql = new StringBuffer("UPDATE I_BPartner i " + "SET R_InterestArea_ID=(SELECT R_InterestArea_ID FROM R_InterestArea ia " + "WHERE i.InterestAreaName=ia.Name AND ia.AD_Client_ID=i.AD_Client_ID) " + "WHERE R_InterestArea_ID IS NULL AND InterestAreaName IS NOT NULL" + " AND I_IsImported='N'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.fine("Set Interest Area=" + no);
    // Value is mandatory error
    sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value is mandatory, ' " + "WHERE Value IS NULL " + " AND I_IsImported<>'Y'").append(clientCheck);
    no = DB.executeUpdateEx(sql.toString(), get_TrxName());
    log.config("Value is mandatory=" + no);
    ModelValidationEngine.get().fireImportValidate(this, null, null, ImportValidator.TIMING_AFTER_VALIDATE);
    commitEx();
    if (p_IsValidateOnly) {
        return "Validated";
    }
    //	-------------------------------------------------------------------
    int noInsert = 0;
    int noUpdate = 0;
    //	Go through Records
    sql = new StringBuffer("SELECT * FROM I_BPartner " + "WHERE I_IsImported='N'").append(clientCheck);
    // gody: 20070113 - Order so the same values are consecutive.
    sql.append(" ORDER BY Value, I_BPartner_ID");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
        rs = pstmt.executeQuery();
        // Remember Previous BP Value BP is only first one, others are contacts.
        // All contacts share BP location.
        // bp and bpl declarations before loop, we need them for data.
        String Old_BPValue = "";
        MBPartner bp = null;
        MBPartnerLocation bpl = null;
        while (rs.next()) {
            // Remember Value - only first occurance of the value is BP
            String New_BPValue = rs.getString("Value");
            X_I_BPartner impBP = new X_I_BPartner(getCtx(), rs, get_TrxName());
            log.fine("I_BPartner_ID=" + impBP.getI_BPartner_ID() + ", C_BPartner_ID=" + impBP.getC_BPartner_ID() + ", C_BPartner_Location_ID=" + impBP.getC_BPartner_Location_ID() + ", AD_User_ID=" + impBP.getAD_User_ID());
            if (!New_BPValue.equals(Old_BPValue)) {
                //	****	Create/Update BPartner	****
                bp = null;
                if (//	Insert new BPartner
                impBP.getC_BPartner_ID() == 0) {
                    bp = new MBPartner(impBP);
                    ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT);
                    setTypeOfBPartner(impBP, bp);
                    if (bp.save()) {
                        impBP.setC_BPartner_ID(bp.getC_BPartner_ID());
                        log.finest("Insert BPartner - " + bp.getC_BPartner_ID());
                        noInsert++;
                    } else {
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert BPartner, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                } else //	Update existing BPartner
                {
                    bp = new MBPartner(getCtx(), impBP.getC_BPartner_ID(), get_TrxName());
                    //		bp.setValue(impBP.getValue());
                    if (impBP.getName() != null) {
                        bp.setName(impBP.getName());
                        bp.setName2(impBP.getName2());
                    }
                    if (impBP.getDUNS() != null)
                        bp.setDUNS(impBP.getDUNS());
                    if (impBP.getTaxID() != null)
                        bp.setTaxID(impBP.getTaxID());
                    if (impBP.getNAICS() != null)
                        bp.setNAICS(impBP.getNAICS());
                    if (impBP.getDescription() != null)
                        bp.setDescription(impBP.getDescription());
                    if (impBP.getC_BP_Group_ID() != 0)
                        bp.setC_BP_Group_ID(impBP.getC_BP_Group_ID());
                    //	Employee values
                    if (impBP.getBirthday() != null)
                        bp.setBirthday(impBP.getBirthday());
                    if (impBP.getFathersName() != null)
                        bp.setFathersName(impBP.getFathersName());
                    if (impBP.getBloodGroup() != null)
                        bp.setBloodGroup(impBP.getBloodGroup());
                    if (impBP.getPlaceOfBirth() != null)
                        bp.setPlaceOfBirth(impBP.getPlaceOfBirth());
                    if (impBP.getGender() != null)
                        bp.setGender(impBP.getGender());
                    //	
                    ModelValidationEngine.get().fireImportValidate(this, impBP, bp, ImportValidator.TIMING_AFTER_IMPORT);
                    setTypeOfBPartner(impBP, bp);
                    //
                    if (bp.save()) {
                        log.finest("Update BPartner - " + bp.getC_BPartner_ID());
                        noUpdate++;
                    } else {
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Update BPartner, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                }
                //	****	Create/Update BPartner Location	****
                bpl = null;
                if (//	Update Location
                impBP.getC_BPartner_Location_ID() != 0) {
                    bpl = new MBPartnerLocation(getCtx(), impBP.getC_BPartner_Location_ID(), get_TrxName());
                    MLocation location = new MLocation(getCtx(), bpl.getC_Location_ID(), get_TrxName());
                    location.setC_Country_ID(impBP.getC_Country_ID());
                    location.setC_Region_ID(impBP.getC_Region_ID());
                    location.setCity(impBP.getCity());
                    location.setAddress1(impBP.getAddress1());
                    location.setAddress2(impBP.getAddress2());
                    location.setPostal(impBP.getPostal());
                    location.setPostal_Add(impBP.getPostal_Add());
                    if (!location.save())
                        log.warning("Location not updated");
                    else
                        bpl.setC_Location_ID(location.getC_Location_ID());
                    if (impBP.getPhone() != null)
                        bpl.setPhone(impBP.getPhone());
                    if (impBP.getPhone2() != null)
                        bpl.setPhone2(impBP.getPhone2());
                    if (impBP.getFax() != null)
                        bpl.setFax(impBP.getFax());
                    ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT);
                    bpl.saveEx();
                } else //	New Location
                if (impBP.getC_Country_ID() != 0 && impBP.getAddress1() != null && impBP.getCity() != null) {
                    MLocation location = new MLocation(getCtx(), impBP.getC_Country_ID(), impBP.getC_Region_ID(), impBP.getCity(), get_TrxName());
                    location.setAddress1(impBP.getAddress1());
                    location.setAddress2(impBP.getAddress2());
                    location.setPostal(impBP.getPostal());
                    location.setPostal_Add(impBP.getPostal_Add());
                    if (location.save())
                        log.finest("Insert Location - " + location.getC_Location_ID());
                    else {
                        rollback();
                        noInsert--;
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert Location, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                    //
                    bpl = new MBPartnerLocation(bp);
                    bpl.setC_Location_ID(location.getC_Location_ID());
                    bpl.setPhone(impBP.getPhone());
                    bpl.setPhone2(impBP.getPhone2());
                    bpl.setFax(impBP.getFax());
                    ModelValidationEngine.get().fireImportValidate(this, impBP, bpl, ImportValidator.TIMING_AFTER_IMPORT);
                    if (bpl.save()) {
                        log.finest("Insert BP Location - " + bpl.getC_BPartner_Location_ID());
                        impBP.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                    } else {
                        rollback();
                        noInsert--;
                        sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert BPLocation, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                        DB.executeUpdateEx(sql.toString(), get_TrxName());
                        continue;
                    }
                }
            }
            Old_BPValue = New_BPValue;
            //	****	Create/Update Contact	****
            MUser user = null;
            if (impBP.getAD_User_ID() != 0) {
                user = new MUser(getCtx(), impBP.getAD_User_ID(), get_TrxName());
                if (user.getC_BPartner_ID() == 0)
                    user.setC_BPartner_ID(bp.getC_BPartner_ID());
                else if (user.getC_BPartner_ID() != bp.getC_BPartner_ID()) {
                    rollback();
                    noInsert--;
                    sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'BP of User <> BP, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                    DB.executeUpdateEx(sql.toString(), get_TrxName());
                    continue;
                }
                if (impBP.getC_Greeting_ID() != 0)
                    user.setC_Greeting_ID(impBP.getC_Greeting_ID());
                String name = impBP.getContactName();
                if (name == null || name.length() == 0)
                    name = impBP.getEMail();
                user.setName(name);
                if (impBP.getTitle() != null)
                    user.setTitle(impBP.getTitle());
                if (impBP.getContactDescription() != null)
                    user.setDescription(impBP.getContactDescription());
                if (impBP.getComments() != null)
                    user.setComments(impBP.getComments());
                if (impBP.getPhone() != null)
                    user.setPhone(impBP.getPhone());
                if (impBP.getPhone2() != null)
                    user.setPhone2(impBP.getPhone2());
                if (impBP.getFax() != null)
                    user.setFax(impBP.getFax());
                if (impBP.getEMail() != null)
                    user.setEMail(impBP.getEMail());
                if (impBP.getBirthday() != null)
                    user.setBirthday(impBP.getBirthday());
                if (bpl != null)
                    user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT);
                if (user.save()) {
                    log.finest("Update BP Contact - " + user.getAD_User_ID());
                } else {
                    rollback();
                    noInsert--;
                    sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Update BP Contact, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                    DB.executeUpdateEx(sql.toString(), get_TrxName());
                    continue;
                }
            } else //	New Contact
            if (impBP.getContactName() != null || impBP.getEMail() != null) {
                user = new MUser(bp);
                if (impBP.getC_Greeting_ID() != 0)
                    user.setC_Greeting_ID(impBP.getC_Greeting_ID());
                String name = impBP.getContactName();
                if (name == null || name.length() == 0)
                    name = impBP.getEMail();
                user.setName(name);
                user.setTitle(impBP.getTitle());
                user.setDescription(impBP.getContactDescription());
                user.setComments(impBP.getComments());
                user.setPhone(impBP.getPhone());
                user.setPhone2(impBP.getPhone2());
                user.setFax(impBP.getFax());
                user.setEMail(impBP.getEMail());
                user.setBirthday(impBP.getBirthday());
                if (bpl != null)
                    user.setC_BPartner_Location_ID(bpl.getC_BPartner_Location_ID());
                ModelValidationEngine.get().fireImportValidate(this, impBP, user, ImportValidator.TIMING_AFTER_IMPORT);
                if (user.save()) {
                    log.finest("Insert BP Contact - " + user.getAD_User_ID());
                    impBP.setAD_User_ID(user.getAD_User_ID());
                } else {
                    rollback();
                    noInsert--;
                    sql = new StringBuffer("UPDATE I_BPartner i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append("'Cannot Insert BPContact, ' ").append("WHERE I_BPartner_ID=").append(impBP.getI_BPartner_ID());
                    DB.executeUpdateEx(sql.toString(), get_TrxName());
                    continue;
                }
            }
            //	Interest Area
            if (impBP.getR_InterestArea_ID() != 0 && user != null) {
                MContactInterest ci = MContactInterest.get(getCtx(), impBP.getR_InterestArea_ID(), user.getAD_User_ID(), true, get_TrxName());
                //	don't subscribe or re-activate
                ci.saveEx();
            }
            //
            impBP.setI_IsImported(true);
            impBP.setProcessed(true);
            impBP.setProcessing(false);
            impBP.saveEx();
            commitEx();
        }
        //	for all I_Product
        DB.close(rs, pstmt);
    } catch (SQLException e) {
        rollback();
        //log.log(Level.SEVERE, "", e);
        throw new DBException(e, sql.toString());
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
        //	Set Error to indicator to not imported
        sql = new StringBuffer("UPDATE I_BPartner " + "SET I_IsImported='N', Updated=SysDate " + "WHERE I_IsImported<>'Y'").append(clientCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        addLog(0, null, new BigDecimal(no), "@Errors@");
        addLog(0, null, new BigDecimal(noInsert), "@C_BPartner_ID@: @Inserted@");
        addLog(0, null, new BigDecimal(noUpdate), "@C_BPartner_ID@: @Updated@");
    }
    return "";
}
Also used : DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) MBPartner(org.compiere.model.MBPartner) X_I_BPartner(org.compiere.model.X_I_BPartner) BigDecimal(java.math.BigDecimal) MBPartnerLocation(org.compiere.model.MBPartnerLocation) MContactInterest(org.compiere.model.MContactInterest) ResultSet(java.sql.ResultSet) MLocation(org.compiere.model.MLocation) MUser(org.compiere.model.MUser)

Aggregations

MBPartner (org.compiere.model.MBPartner)78 BigDecimal (java.math.BigDecimal)21 ResultSet (java.sql.ResultSet)14 MBPartnerLocation (org.compiere.model.MBPartnerLocation)14 AdempiereException (org.adempiere.exceptions.AdempiereException)13 MLocation (org.compiere.model.MLocation)13 MOrder (org.compiere.model.MOrder)13 PreparedStatement (java.sql.PreparedStatement)11 MOrderLine (org.compiere.model.MOrderLine)11 MUser (org.compiere.model.MUser)11 MInvoice (org.compiere.model.MInvoice)10 MOrg (org.compiere.model.MOrg)9 Query (org.compiere.model.Query)9 MWarehouse (org.compiere.model.MWarehouse)8 SQLException (java.sql.SQLException)7 MClient (org.compiere.model.MClient)7 MInvoiceLine (org.compiere.model.MInvoiceLine)7 AdempiereUserError (org.compiere.util.AdempiereUserError)7 Timestamp (java.sql.Timestamp)6 MDDOrder (org.eevolution.model.MDDOrder)6