Search in sources :

Example 76 with MInvoice

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

the class WPayment method saveChangesInTrx.

// saveChanges
/**************************************************************************
	 *	Save Changes
	 *	@return true, if eindow can exit
	 */
private boolean saveChangesInTrx(final String trxName) {
    // set trxname for class objects
    if (m_cashLine != null)
        m_cashLine.set_TrxName(trxName);
    if (m_mPayment != null)
        m_mPayment.set_TrxName(trxName);
    if (m_mPaymentOriginal != null)
        m_mPaymentOriginal.set_TrxName(trxName);
    ValueNamePair vp = paymentCombo.getSelectedItem().toValueNamePair();
    String newPaymentRule = vp.getValue();
    log.info("New Rule: " + newPaymentRule);
    //  only Payment Rule
    if (m_onlyRule) {
        if (!newPaymentRule.equals(m_PaymentRule))
            m_mTab.setValue("PaymentRule", newPaymentRule);
        return true;
    }
    //	New Values
    Timestamp newDateAcct = m_DateAcct;
    int newC_PaymentTerm_ID = m_C_PaymentTerm_ID;
    int newC_CashLine_ID = m_C_CashLine_ID;
    int newC_CashBook_ID = m_C_CashBook_ID;
    String newCCType = m_CCType;
    int newC_BankAccount_ID = 0;
    String payTypes = m_Cash_As_Payment ? "KTSDB" : "KTSD";
    //	B (Cash)		(Currency)
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) {
        if (m_Cash_As_Payment) {
            // get bank account
            ListItem selected = bBankAccountCombo.getSelectedItem();
            KeyNamePair kp = selected != null ? selected.toKeyNamePair() : null;
            if (kp != null)
                newC_BankAccount_ID = kp.getKey();
        } else {
            // get cash book
            ListItem selected = bCashBookCombo.getSelectedItem();
            KeyNamePair kp = selected != null ? selected.toKeyNamePair() : null;
            if (kp != null)
                newC_CashBook_ID = kp.getKey();
        }
        newDateAcct = (Timestamp) bDateField.getValue();
        // Get changes to cash amount
        m_mPayment.setAmount(m_C_Currency_ID, (BigDecimal) bAmountField.getValue());
        m_Amount = (BigDecimal) bAmountField.getValue();
    } else //	K (CreditCard)  Type, Number, Exp, Approval
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_CreditCard)) {
        ListItem selected = kTypeCombo.getSelectedItem();
        vp = selected != null ? selected.toValueNamePair() : null;
        if (vp != null)
            newCCType = vp.getValue();
    } else //	T (Transfer)	BPartner_Bank
    if (newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) || newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) {
        tAccountCombo.getSelectedItem();
    } else //	P (PaymentTerm)	PaymentTerm
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_OnCredit)) {
        ListItem selected = pTermCombo.getSelectedItem();
        KeyNamePair kp = selected != null ? selected.toKeyNamePair() : null;
        if (kp != null)
            newC_PaymentTerm_ID = kp.getKey();
    } else //	S (Check)		(Currency) CheckNo, Routing
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Check)) {
        ListItem selected = sBankAccountCombo.getSelectedItem();
        KeyNamePair kp = selected != null ? selected.toKeyNamePair() : null;
        if (kp != null)
            newC_BankAccount_ID = kp.getKey();
    } else
        return false;
    /***********************
		 *  Changed PaymentRule
		 */
    if (!newPaymentRule.equals(m_PaymentRule)) {
        log.fine("Changed PaymentRule: " + m_PaymentRule + " -> " + newPaymentRule);
        //  We had a CashBook Entry
        if (m_PaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) {
            log.fine("Old Cash - " + m_cashLine);
            if (m_cashLine != null) {
                MCashLine cl = m_cashLine.createReversal();
                if (cl.save())
                    log.config("CashCancelled");
                else
                    FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled");
            }
            //  reset
            newC_CashLine_ID = 0;
        } else //  We had a change in Payment type (e.g. Check to CC)
        if (payTypes.indexOf(m_PaymentRule) != -1 && payTypes.indexOf(newPaymentRule) != -1 && m_mPaymentOriginal != null) {
            log.fine("Old Payment(1) - " + m_mPaymentOriginal);
            m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct);
            boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct);
            m_mPaymentOriginal.saveEx();
            if (ok)
                log.info("Payment Canecelled - " + m_mPaymentOriginal);
            else
                FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPaymentOriginal.getDocumentNo());
            m_mPayment.resetNew();
        } else //	We had a Payment and something else (e.g. Check to Cash)
        if (payTypes.indexOf(m_PaymentRule) != -1 && payTypes.indexOf(newPaymentRule) == -1) {
            log.fine("Old Payment(2) - " + m_mPaymentOriginal);
            if (m_mPaymentOriginal != null) {
                m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct);
                boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct);
                m_mPaymentOriginal.saveEx();
                if (//  Cancel Payment
                ok) {
                    log.fine("PaymentCancelled " + m_mPayment.getDocumentNo());
                    m_mTab.getTableModel().dataSave(true);
                    m_mPayment.resetNew();
                    m_mPayment.setAmount(m_C_Currency_ID, m_Amount);
                } else
                    FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPayment.getDocumentNo());
            }
        }
    }
    //  Get Order and optionally Invoice
    int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID");
    int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID");
    if (C_Invoice_ID == 0 && m_DocStatus.equals("CO"))
        C_Invoice_ID = getInvoiceID(C_Order_ID);
    //  Amount sign negative, if ARC (Credit Memo) or API (AP Invoice)
    boolean negateAmt = false;
    MInvoice invoice = null;
    if (C_Invoice_ID != 0) {
        invoice = new MInvoice(Env.getCtx(), C_Invoice_ID, null);
        negateAmt = invoice.isCreditMemo();
    }
    MOrder order = null;
    if (invoice == null && C_Order_ID != 0)
        order = new MOrder(Env.getCtx(), C_Order_ID, null);
    BigDecimal payAmount = m_Amount;
    if (negateAmt)
        payAmount = m_Amount.negate();
    // Info
    log.config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt);
    /***********************
		 *  CashBook
		 */
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash) && !m_Cash_As_Payment) {
        log.fine("Cash");
        if (C_Invoice_ID == 0 && order == null) {
            log.config("No Invoice!");
            FDialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated");
        } else {
            payAmount = (BigDecimal) bAmountField.getValue();
            //  Changed Amount
            if (m_cashLine != null && payAmount.compareTo(m_cashLine.getAmount()) != 0) {
                log.config("Changed CashBook Amount");
                m_cashLine.setAmount((BigDecimal) bAmountField.getValue());
                m_cashLine.saveEx();
            }
            //	Different Date/CashBook
            if (m_cashLine != null && (newC_CashBook_ID != m_C_CashBook_ID || !TimeUtil.isSameDay(m_cashLine.getStatementDate(), newDateAcct))) {
                log.config("Changed CashBook/Date: " + m_C_CashBook_ID + "->" + newC_CashBook_ID);
                MCashLine reverse = m_cashLine.createReversal();
                reverse.saveEx();
                m_cashLine = null;
            }
            //	Create new
            if (m_cashLine == null) {
                log.config("New CashBook");
                int C_Currency_ID = 0;
                if (invoice != null)
                    C_Currency_ID = invoice.getC_Currency_ID();
                if (C_Currency_ID == 0 && order != null)
                    C_Currency_ID = order.getC_Currency_ID();
                MCash cash = null;
                if (newC_CashBook_ID != 0)
                    cash = MCash.get(Env.getCtx(), newC_CashBook_ID, newDateAcct, null);
                else
                    //	Default
                    cash = MCash.get(Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, null);
                if (cash == null || cash.get_ID() == 0)
                    FDialog.error(m_WindowNo, this, "PaymentError", CLogger.retrieveErrorString("CashNotCreated"));
                else {
                    MCashLine cl = new MCashLine(cash);
                    //ADialog.info(m_WindowNo, this, "m_cashLine - New Cashbook", "Amount: "+cl.getAmount());
                    if (invoice != null)
                        // overrides amount
                        cl.setInvoice(invoice);
                    if (order != null) {
                        // overrides amount
                        cl.setOrder(order, null);
                        m_needSave = true;
                    }
                    cl.setAmount((BigDecimal) bAmountField.getValue());
                    cl.saveEx();
                    log.config("CashCreated");
                    if (invoice == null && C_Invoice_ID != 0) {
                        invoice = new MInvoice(Env.getCtx(), C_Invoice_ID, null);
                    }
                    if (invoice != null) {
                        invoice.setC_CashLine_ID(cl.getC_CashLine_ID());
                        invoice.saveEx(trxName);
                    }
                    if (order == null && C_Order_ID != 0) {
                        order = new MOrder(Env.getCtx(), C_Order_ID, null);
                    }
                    if (order != null) {
                        order.setC_CashLine_ID(cl.getC_CashLine_ID());
                        order.saveEx(trxName);
                    }
                    log.config("Update Order & Invoice with CashLine");
                }
            }
        }
    //	have invoice
    }
    /***********************
		 *  Payments
		 */
    if (("KS".indexOf(newPaymentRule) != -1) || (newPaymentRule.equals(MOrder.PAYMENTRULE_Cash) && m_Cash_As_Payment)) {
        log.fine("Payment - " + newPaymentRule);
        //  Set Amount
        m_mPayment.setAmount(m_C_Currency_ID, payAmount);
        if (newPaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) {
            m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, newCCType, kNumberField.getText(), "", kExpField.getText());
            // Get changes to credit card amount
            m_mPayment.setAmount(m_C_Currency_ID, (BigDecimal) kAmountField.getValue());
            m_mPayment.setPaymentProcessor();
        } else if (newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) || newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) {
            m_mPayment.setBankACH(newC_BankAccount_ID, m_isSOTrx, newPaymentRule, tRoutingField.getText(), tNumberField.getText());
            m_mPayment.setAmount(m_C_Currency_ID, payAmount);
        } else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Check)) {
            m_mPayment.setBankCheck(newC_BankAccount_ID, m_isSOTrx, sRoutingField.getText(), sNumberField.getText(), sCheckField.getText());
            // Get changes to check amount
            m_mPayment.setAmount(m_C_Currency_ID, (BigDecimal) sAmountField.getValue());
        } else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Cash)) {
            // Get changes to cash amount
            m_mPayment.setTenderType(MPayment.TENDERTYPE_Cash);
            m_mPayment.setBankCash(newC_BankAccount_ID, m_isSOTrx, MPayment.TENDERTYPE_Cash);
            m_mPayment.setAmount(m_C_Currency_ID, payAmount);
        }
        m_mPayment.setC_BPartner_ID(m_C_BPartner_ID);
        m_mPayment.setC_Invoice_ID(C_Invoice_ID);
        if (order != null) {
            m_mPayment.setC_Order_ID(C_Order_ID);
            m_needSave = true;
        }
        m_mPayment.setDateTrx(m_DateAcct);
        m_mPayment.setDateAcct(m_DateAcct);
        m_mPayment.saveEx();
        //  Save/Post
        if (m_mPayment.get_ID() > 0 && MPayment.DOCSTATUS_Drafted.equals(m_mPayment.getDocStatus())) {
            boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete);
            m_mPayment.saveEx();
            if (ok)
                FDialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo());
            else
                FDialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated");
        } else
            log.fine("NotDraft " + m_mPayment);
    }
    /**********************
		 *	Save Values to mTab
		 */
    log.config("Saving changes");
    //
    if (!newPaymentRule.equals(m_PaymentRule))
        m_mTab.setValue("PaymentRule", newPaymentRule);
    //
    if (!newDateAcct.equals(m_DateAcct))
        m_mTab.setValue("DateAcct", newDateAcct);
    //
    if (newC_PaymentTerm_ID != m_C_PaymentTerm_ID)
        m_mTab.setValue("C_PaymentTerm_ID", new Integer(newC_PaymentTerm_ID));
    //	Set Payment
    if (m_mPayment.getC_Payment_ID() != m_C_Payment_ID) {
        if (m_mPayment.getC_Payment_ID() == 0)
            m_mTab.setValue("C_Payment_ID", null);
        else
            m_mTab.setValue("C_Payment_ID", new Integer(m_mPayment.getC_Payment_ID()));
    }
    //	Set Cash
    if (newC_CashLine_ID != m_C_CashLine_ID) {
        if (newC_CashLine_ID == 0)
            m_mTab.setValue("C_CashLine_ID", null);
        else
            m_mTab.setValue("C_CashLine_ID", new Integer(newC_CashLine_ID));
    }
    return true;
}
Also used : MInvoice(org.compiere.model.MInvoice) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) MCashLine(org.compiere.model.MCashLine) MOrder(org.compiere.model.MOrder) ValueNamePair(org.compiere.util.ValueNamePair) ListItem(org.adempiere.webui.component.ListItem) KeyNamePair(org.compiere.util.KeyNamePair) MCash(org.compiere.model.MCash)

Example 77 with MInvoice

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

the class WPayment method onPaymentComboSelection.

private void onPaymentComboSelection() {
    //	get selection
    ListItem selectedItem = paymentCombo.getSelectedItem();
    ValueNamePair pp = selectedItem != null ? selectedItem.toValueNamePair() : null;
    if (pp != null) {
        String s = pp.getValue().toLowerCase();
        if (X_C_Order.PAYMENTRULE_DirectDebit.equalsIgnoreCase(s))
            s = X_C_Order.PAYMENTRULE_DirectDeposit.toLowerCase();
        s += "Panel";
        //	switch to panel
        show(s);
        //Bojana&Daniel
        //If Invoice is Vendor invoice then Cash has to be created by negative amount
        int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID");
        MInvoice invoice_tmp = new MInvoice(Env.getCtx(), C_Invoice_ID, null);
        if (!invoice_tmp.isSOTrx()) {
            bAmountField.setValue(m_Amount.negate());
        } else {
            bAmountField.setValue(m_Amount);
        }
        invoice_tmp = null;
    }
}
Also used : MInvoice(org.compiere.model.MInvoice) ListItem(org.adempiere.webui.component.ListItem) ValueNamePair(org.compiere.util.ValueNamePair)

Example 78 with MInvoice

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

the class InvoiceNGL method createGLJournal.

//	doIt
/**
	 * 	Create GL Journal
	 * 	@return document info
	 */
private String createGLJournal() {
    //FR: [ 2214883 ] Remove SQL code and Replace for Query
    final String whereClause = "AD_PInstance_ID=?";
    List<X_T_InvoiceGL> list = new Query(getCtx(), X_T_InvoiceGL.Table_Name, whereClause, get_TrxName()).setParameters(getAD_PInstance_ID()).setOrderBy("AD_Org_ID").list();
    if (list.size() == 0)
        return " - No Records found";
    //
    MAcctSchema as = MAcctSchema.get(getCtx(), p_C_AcctSchema_ID);
    MAcctSchemaDefault asDefaultAccts = MAcctSchemaDefault.get(getCtx(), p_C_AcctSchema_ID);
    MGLCategory cat = MGLCategory.getDefaultSystem(getCtx());
    if (cat == null) {
        MDocType docType = MDocType.get(getCtx(), p_C_DocTypeReval_ID);
        cat = MGLCategory.get(getCtx(), docType.getGL_Category_ID());
    }
    //
    MJournalBatch batch = new MJournalBatch(getCtx(), 0, get_TrxName());
    batch.setDescription(getName());
    batch.setC_DocType_ID(p_C_DocTypeReval_ID);
    batch.setDateDoc(new Timestamp(System.currentTimeMillis()));
    batch.setDateAcct(p_DateReval);
    batch.setC_Currency_ID(as.getC_Currency_ID());
    if (!batch.save())
        return " - Could not create Batch";
    //
    MJournal journal = null;
    BigDecimal drTotal = Env.ZERO;
    BigDecimal crTotal = Env.ZERO;
    int AD_Org_ID = 0;
    for (int i = 0; i < list.size(); i++) {
        X_T_InvoiceGL gl = list.get(i);
        if (gl.getAmtRevalDrDiff().signum() == 0 && gl.getAmtRevalCrDiff().signum() == 0)
            continue;
        MInvoice invoice = new MInvoice(getCtx(), gl.getC_Invoice_ID(), null);
        if (invoice.getC_Currency_ID() == as.getC_Currency_ID())
            continue;
        //
        if (journal == null) {
            journal = new MJournal(batch);
            journal.setC_AcctSchema_ID(as.getC_AcctSchema_ID());
            journal.setC_Currency_ID(as.getC_Currency_ID());
            journal.setC_ConversionType_ID(p_C_ConversionTypeReval_ID);
            MOrg org = MOrg.get(getCtx(), gl.getAD_Org_ID());
            journal.setDescription(getName() + " - " + org.getName());
            journal.setGL_Category_ID(cat.getGL_Category_ID());
            if (!journal.save())
                return " - Could not create Journal";
        }
        //
        MJournalLine line = new MJournalLine(journal);
        line.setLine((i + 1) * 10);
        line.setDescription(invoice.getSummary());
        //
        MFactAcct fa = new MFactAcct(getCtx(), gl.getFact_Acct_ID(), null);
        line.setC_ValidCombination_ID(MAccount.get(fa));
        BigDecimal dr = gl.getAmtRevalDrDiff();
        BigDecimal cr = gl.getAmtRevalCrDiff();
        drTotal = drTotal.add(dr);
        crTotal = crTotal.add(cr);
        line.setAmtSourceDr(dr);
        line.setAmtAcctDr(dr);
        line.setAmtSourceCr(cr);
        line.setAmtAcctCr(cr);
        line.saveEx();
        //
        if (//	invoice org id
        AD_Org_ID == 0)
            AD_Org_ID = gl.getAD_Org_ID();
        //	Change in Org
        if (AD_Org_ID != gl.getAD_Org_ID()) {
            createBalancing(asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (i + 1) * 10);
            //
            AD_Org_ID = gl.getAD_Org_ID();
            drTotal = Env.ZERO;
            crTotal = Env.ZERO;
            journal = null;
        }
    }
    createBalancing(asDefaultAccts, journal, drTotal, crTotal, AD_Org_ID, (list.size() + 1) * 10);
    return " - " + batch.getDocumentNo() + " #" + list.size();
}
Also used : MDocType(org.compiere.model.MDocType) Query(org.compiere.model.Query) X_T_InvoiceGL(org.compiere.model.X_T_InvoiceGL) MGLCategory(org.compiere.model.MGLCategory) MJournalLine(org.compiere.model.MJournalLine) MInvoice(org.compiere.model.MInvoice) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) MAcctSchema(org.compiere.model.MAcctSchema) MOrg(org.compiere.model.MOrg) MAcctSchemaDefault(org.compiere.model.MAcctSchemaDefault) MFactAcct(org.compiere.model.MFactAcct) MJournal(org.compiere.model.MJournal) MJournalBatch(org.compiere.model.MJournalBatch)

Example 79 with MInvoice

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

the class InvoiceCreateFrom method doIt.

@Override
protected String doIt() throws Exception {
    // Valid Record Identifier
    if (getRecord_ID() == 0)
        return "";
    //	Get Shipment
    MInvoice invoice = new MInvoice(getCtx(), getRecord_ID(), get_TrxName());
    AtomicInteger referenceId = new AtomicInteger(0);
    AtomicInteger created = new AtomicInteger(0);
    List<Integer> recordIds = getSelectionKeys();
    String createFromType = recordIds.size() > 0 ? getSelectionAsString(recordIds.get(0), "CF_CreateFromType") : null;
    log.fine("CreateFromType=" + createFromType);
    if (createFromType == null || createFromType.length() == 0)
        throw new AdempiereException("@CreateFromType@ @NotFound@");
    //	Loop
    recordIds.stream().forEach(key -> {
        int productId = getSelectionAsInt(key, "CF_M_Product_ID");
        int chargeId = getSelectionAsInt(key, "CF_C_Charge_ID");
        int uomId = getSelectionAsInt(key, "CF_C_UOM_ID");
        BigDecimal qtyEntered = getSelectionAsBigDecimal(key, "CF_QtyEntered");
        log.fine("Line QtyEntered=" + qtyEntered + ", Product=" + productId + ", CreateFromType=" + createFromType + ", Key=" + key);
        MInvoiceLine invoiceLine = new MInvoiceLine(invoice);
        BigDecimal qtyInvoiced = null;
        int precision = 2;
        if (productId > 0) {
            MProduct product = MProduct.get(Env.getCtx(), productId);
            if (product != null) {
                invoiceLine.setM_Product_ID(product.getM_Product_ID(), uomId);
                precision = product.getUOMPrecision();
                if (product.getC_UOM_ID() != uomId) {
                    qtyEntered = qtyEntered.setScale(precision, BigDecimal.ROUND_HALF_DOWN);
                    qtyInvoiced = MUOMConversion.convertProductFrom(Env.getCtx(), productId, uomId, qtyEntered);
                }
            }
        } else if (chargeId != 0) {
            invoiceLine.setC_Charge_ID(chargeId);
        }
        qtyEntered = qtyEntered.setScale(precision, BigDecimal.ROUND_HALF_DOWN);
        if (qtyInvoiced == null)
            qtyInvoiced = qtyEntered;
        invoiceLine.setQty(qtyEntered);
        invoiceLine.setQtyInvoiced(qtyInvoiced);
        if (createFromType.equals(ORDER)) {
            MOrderLine orderLine = new MOrderLine(getCtx(), key, get_TrxName());
            referenceId.set(orderLine.getC_Order_ID());
            String whereClause = "EXISTS (SELECT 1 " + "FROM M_InOut io " + "WHERE io.M_InOut_ID = M_InOutLine.M_InOut_ID " + "AND io.DocStatus IN ('CO','CL'))";
            MInOutLine[] inOutLines = MInOutLine.getOfOrderLine(Env.getCtx(), key, whereClause, get_TrxName());
            log.fine("Receipt Lines with OrderLine = #" + inOutLines.length);
            final BigDecimal qty = qtyEntered;
            MInOutLine inOutLine = Arrays.stream(inOutLines).filter(ioLine -> ioLine != null && ioLine.getQtyEntered().compareTo(qty) == 0).findFirst().orElse(inOutLines.length > 0 ? inOutLines[0] : null);
            if (inOutLine != null)
                invoiceLine.setShipLine(inOutLine);
            else
                invoiceLine.setOrderLine(orderLine);
        } else if (createFromType.equals(INVOICE)) {
            MInvoiceLine fromLine = new MInvoiceLine(getCtx(), key, get_TrxName());
            referenceId.set(invoiceLine.getParent().getC_Invoice_ID());
            PO.copyValues(fromLine, invoiceLine);
            invoiceLine.setC_Invoice_ID(invoiceLine.getParent().getC_Invoice_ID());
            invoiceLine.setAD_Org_ID(fromLine.getAD_Org_ID());
            invoiceLine.setC_OrderLine_ID(0);
            invoiceLine.setRef_InvoiceLine_ID(0);
            invoiceLine.setM_InOutLine_ID(0);
            invoiceLine.setA_Asset_ID(0);
            invoiceLine.setM_AttributeSetInstance_ID(0);
            invoiceLine.setS_ResourceAssignment_ID(0);
            if (invoiceLine.getParent().getC_BPartner_ID() != fromLine.getC_Invoice().getC_BPartner_ID())
                invoiceLine.setTax();
            invoiceLine.setProcessed(false);
        } else if (createFromType.equals(RMA)) {
            MRMALine rmaLine = new MRMALine(getCtx(), key, get_TrxName());
            referenceId.set(rmaLine.getM_RMA_ID());
            invoiceLine.setRMALine(rmaLine);
        } else if (createFromType.equals(RECEIPT)) {
            MInOutLine inOutLine = new MInOutLine(getCtx(), key, get_TrxName());
            referenceId.set(inOutLine.getM_InOut_ID());
            invoiceLine.setShipLine(inOutLine);
        }
        invoiceLine.saveEx();
        if (createFromType.equals(INVOICE)) {
            MInvoiceLine fromLine = new MInvoiceLine(getCtx(), key, get_TrxName());
            invoiceLine.copyLandedCostFrom(fromLine);
            invoiceLine.allocateLandedCosts();
        }
        created.updateAndGet(createNo -> createNo + 1);
    });
    //	Add reference to Order / Invoice / RMA
    addReference(invoice, createFromType, referenceId.get());
    return "@Created@ " + created.get();
}
Also used : MProduct(org.compiere.model.MProduct) MInOutLine(org.compiere.model.MInOutLine) MInvoiceLine(org.compiere.model.MInvoiceLine) MInvoice(org.compiere.model.MInvoice) BigDecimal(java.math.BigDecimal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AdempiereException(org.adempiere.exceptions.AdempiereException) MOrderLine(org.compiere.model.MOrderLine) MRMALine(org.compiere.model.MRMALine)

Example 80 with MInvoice

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

the class InvoiceWriteOff method writeOff.

//	doIt
/**
	 * 	Write Off
	 *	@param invoiceId invoice
	 *	@param documentNo doc no
	 *	@param dateInvoiced date
	 *	@param currencyId currency
	 *	@param openAmt open amt
	 *	@return true if written off
	 */
private boolean writeOff(int invoiceId, String documentNo, Timestamp dateInvoiced, int currencyId, BigDecimal openAmt) {
    //	Nothing to do
    if (openAmt == null || openAmt.signum() == 0)
        return false;
    if (openAmt.abs().compareTo(getMaximumWriteOffperInvoice()) >= 0)
        return false;
    //
    if (isSimulation()) {
        addLog("@IsSimulation@");
        addLog(invoiceId, dateInvoiced, openAmt, documentNo);
        return true;
    }
    //	Invoice
    MInvoice invoice = new MInvoice(getCtx(), invoiceId, get_TrxName());
    if (!invoice.isSOTrx())
        openAmt = openAmt.negate();
    //	Allocation
    if (allocation == null || currencyId != allocation.getC_Currency_ID()) {
        processAllocation();
        allocation = new MAllocationHdr(getCtx(), true, getAccountDate(), currencyId, getProcessInfo().getTitle() + " #" + getAD_PInstance_ID(), get_TrxName());
        allocation.setAD_Org_ID(invoice.getAD_Org_ID());
        if (!allocation.save()) {
            log.log(Level.SEVERE, "Cannot create allocation header");
            return false;
        }
    }
    //	Payment
    if (isCreatePayment() && (payment == null || invoice.getC_BPartner_ID() != payment.getC_BPartner_ID() || currencyId != payment.getC_Currency_ID())) {
        processPayment();
        payment = new MPayment(getCtx(), 0, get_TrxName());
        payment.setAD_Org_ID(invoice.getAD_Org_ID());
        payment.setC_BankAccount_ID(getBankAccountId());
        payment.setTenderType(MPayment.TENDERTYPE_Check);
        payment.setDateTrx(getAccountDate());
        payment.setDateAcct(getAccountDate());
        payment.setDescription(getProcessInfo().getTitle() + " #" + getAD_PInstance_ID());
        payment.setC_BPartner_ID(invoice.getC_BPartner_ID());
        //	payments are negative
        payment.setIsReceipt(true);
        payment.setC_Currency_ID(currencyId);
        if (!payment.save()) {
            log.log(Level.SEVERE, "Cannot create payment");
            return false;
        }
    }
    //	Line
    MAllocationLine allocationLine = null;
    if (isCreatePayment()) {
        allocationLine = new MAllocationLine(allocation, openAmt, Env.ZERO, Env.ZERO, Env.ZERO);
        payment.setPayAmt(payment.getPayAmt().add(openAmt));
        allocationLine.setC_Payment_ID(payment.getC_Payment_ID());
    } else
        allocationLine = new MAllocationLine(allocation, Env.ZERO, Env.ZERO, openAmt, Env.ZERO);
    allocationLine.setC_Invoice_ID(invoiceId);
    if (allocationLine.save()) {
        addLog(invoiceId, dateInvoiced, openAmt, documentNo);
        return true;
    }
    //	Error
    log.log(Level.SEVERE, "Cannot create allocation line for C_Invoice_ID=" + invoiceId);
    return false;
}
Also used : MPayment(org.compiere.model.MPayment) MInvoice(org.compiere.model.MInvoice) MAllocationLine(org.compiere.model.MAllocationLine) MAllocationHdr(org.compiere.model.MAllocationHdr)

Aggregations

MInvoice (org.compiere.model.MInvoice)98 BigDecimal (java.math.BigDecimal)29 MInvoiceLine (org.compiere.model.MInvoiceLine)27 MPayment (org.compiere.model.MPayment)16 MBPartner (org.compiere.model.MBPartner)15 MOrder (org.compiere.model.MOrder)15 MInOut (org.compiere.model.MInOut)14 ResultSet (java.sql.ResultSet)13 PreparedStatement (java.sql.PreparedStatement)12 Timestamp (java.sql.Timestamp)11 MDocType (org.compiere.model.MDocType)9 MInOutLine (org.compiere.model.MInOutLine)8 MOrderLine (org.compiere.model.MOrderLine)7 SQLException (java.sql.SQLException)6 ArrayList (java.util.ArrayList)6 AdempiereException (org.adempiere.exceptions.AdempiereException)5 MClient (org.compiere.model.MClient)5 MLocation (org.compiere.model.MLocation)5 KeyNamePair (org.compiere.util.KeyNamePair)5 ValueNamePair (org.compiere.util.ValueNamePair)5