Search in sources :

Example 86 with MInvoice

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

the class CreateFromShipment method getInvoiceData.

/**
	 * Load Invoice details
	 * @param C_Invoice_ID Invoice
	 */
protected Vector<Vector<Object>> getInvoiceData(int C_Invoice_ID) {
    // save
    m_invoice = new MInvoice(Env.getCtx(), C_Invoice_ID, null);
    p_order = null;
    m_rma = null;
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    StringBuffer sql = new StringBuffer(// Entered UOM
    "SELECT " + "l.QtyInvoiced-SUM(NVL(mi.Qty,0)),l.QtyEntered/l.QtyInvoiced," + // 3..4
    " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name)," + // 5..6
    " p.M_Locator_ID, loc.Value, " + // 7..11
    " l.M_Product_ID,p.Name, po.VendorProductNo, l.C_InvoiceLine_ID,l.Line," + // 12
    " l.C_OrderLine_ID " + " FROM C_InvoiceLine l ");
    if (Env.isBaseLanguage(Env.getCtx(), "C_UOM"))
        sql.append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
    else
        sql.append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='").append(Env.getAD_Language(Env.getCtx())).append("')");
    sql.append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)").append(" LEFT OUTER JOIN M_Locator loc on (p.M_Locator_ID=loc.M_Locator_ID)").append(" INNER JOIN C_Invoice inv ON (l.C_Invoice_ID=inv.C_Invoice_ID)").append(" LEFT OUTER JOIN M_Product_PO po ON (l.M_Product_ID = po.M_Product_ID AND inv.C_BPartner_ID = po.C_BPartner_ID)").append(" LEFT OUTER JOIN M_MatchInv mi ON (l.C_InvoiceLine_ID=mi.C_InvoiceLine_ID)").append(" WHERE l.C_Invoice_ID=? AND l.QtyInvoiced<>0 ").append("GROUP BY l.QtyInvoiced,l.QtyEntered/l.QtyInvoiced," + "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name)," + "p.M_Locator_ID, loc.Value, " + "l.M_Product_ID,p.Name, po.VendorProductNo, l.C_InvoiceLine_ID,l.Line,l.C_OrderLine_ID ").append("ORDER BY l.Line");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql.toString(), null);
        pstmt.setInt(1, C_Invoice_ID);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            Vector<Object> line = new Vector<Object>(7);
            // 0-Selection
            line.add(new Boolean(false));
            BigDecimal qtyInvoiced = rs.getBigDecimal(1);
            BigDecimal multiplier = rs.getBigDecimal(2);
            BigDecimal qtyEntered = qtyInvoiced.multiply(multiplier);
            // 1-Qty
            line.add(qtyEntered);
            KeyNamePair pp = new KeyNamePair(rs.getInt(3), rs.getString(4).trim());
            // 2-UOM
            line.add(pp);
            // Add locator
            // 3-Locator
            line.add(getLocatorKeyNamePair(rs.getInt(5)));
            pp = new KeyNamePair(rs.getInt(7), rs.getString(8));
            // 4-Product
            line.add(pp);
            // 5-VendorProductNo
            line.add(rs.getString(9));
            int C_OrderLine_ID = rs.getInt(12);
            if (rs.wasNull())
                // 6-Order
                line.add(null);
            else
                line.add(new KeyNamePair(C_OrderLine_ID, "."));
            // 7-Ship
            line.add(null);
            pp = new KeyNamePair(rs.getInt(10), rs.getString(11));
            // 8-Invoice
            line.add(pp);
            data.add(line);
        }
    } catch (SQLException e) {
        log.log(Level.SEVERE, sql.toString(), e);
    //throw new DBException(e, sql);
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    return data;
}
Also used : SQLException(java.sql.SQLException) MInvoice(org.compiere.model.MInvoice) PreparedStatement(java.sql.PreparedStatement) BigDecimal(java.math.BigDecimal) ResultSet(java.sql.ResultSet) KeyNamePair(org.compiere.util.KeyNamePair) Vector(java.util.Vector)

Example 87 with MInvoice

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

the class VPayment method saveChangesInTrx.

// saveChanges
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 = (ValueNamePair) paymentCombo.getSelectedItem();
    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
            KeyNamePair kp = (KeyNamePair) sBankAccountCombo.getSelectedItem();
            if (kp != null)
                newC_BankAccount_ID = kp.getKey();
        } else {
            // get cash book
            KeyNamePair kp = (KeyNamePair) bCashBookCombo.getSelectedItem();
            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)) {
        vp = (ValueNamePair) kTypeCombo.getSelectedItem();
        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)) {
        KeyNamePair kp = (KeyNamePair) pTermCombo.getSelectedItem();
        if (kp != null)
            newC_PaymentTerm_ID = kp.getKey();
    } else //	S (Check)		(Currency) CheckNo, Routing
    if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Check)) {
        //	sCurrencyCombo.getSelectedItem();
        KeyNamePair kp = (KeyNamePair) sBankAccountCombo.getSelectedItem();
        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) && !m_Cash_As_Payment) {
            log.fine("Old Cash - " + m_cashLine);
            if (m_cashLine != null) {
                MCashLine cl = m_cashLine.createReversal();
                cl.saveEx();
            }
            //  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 Cancelled - " + m_mPaymentOriginal);
            else
                ADialog.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
                    ADialog.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, trxName);
    //  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, trxName);
        negateAmt = invoice.isCreditMemo();
    }
    MOrder order = null;
    if (invoice == null && C_Order_ID != 0)
        order = new MOrder(Env.getCtx(), C_Order_ID, trxName);
    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!");
            ADialog.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(payAmount);
                m_cashLine.setAmount((BigDecimal) bAmountField.getValue());
                // ADialog.info(m_WindowNo, this, "m_cashLine - Changed Amount", "Amount: "+m_cashLine.getAmount());
                m_cashLine.saveEx();
                log.config("CashAmt Changed");
            }
            //	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, trxName);
                else
                    //	Default
                    cash = MCash.get(Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, trxName);
                if (cash == null || cash.get_ID() == 0)
                    ADialog.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, trxName);
                        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, trxName);
                    }
                    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, trxName);
                    }
                    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());
            m_mPayment.setA_Name(kNameField.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)
                ADialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo());
            else
                ADialog.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 : MOrder(org.compiere.model.MOrder) MInvoice(org.compiere.model.MInvoice) ValueNamePair(org.compiere.util.ValueNamePair) KeyNamePair(org.compiere.util.KeyNamePair) Timestamp(java.sql.Timestamp) MCash(org.compiere.model.MCash) BigDecimal(java.math.BigDecimal) MCashLine(org.compiere.model.MCashLine)

Example 88 with MInvoice

use of org.compiere.model.MInvoice in project lar_361 by comitsrl.

the class InvoiceGenerate method createLine.

// createLine
/**
 * 	Create Invoice Line from Shipment
 *	@param order order
 *	@param ship shipment header
 *	@param sLine shipment line
 */
private void createLine(MOrder order, MInOut ship, MInOutLine sLine) {
    if (m_invoice == null) {
        m_invoice = new MInvoice(order, 0, p_DateInvoiced);
        // @emmie custom
        m_invoice.set_ValueOfColumn("C_POS_ID", p_C_POS_ID);
        // @emmie custom
        if (!m_invoice.save())
            throw new IllegalStateException("Could not create Invoice (s)");
    }
    // Create Shipment Comment Line
    if (m_ship == null || m_ship.getM_InOut_ID() != ship.getM_InOut_ID()) {
        MDocType dt = MDocType.get(getCtx(), ship.getC_DocType_ID());
        if (m_bp == null || m_bp.getC_BPartner_ID() != ship.getC_BPartner_ID())
            m_bp = new MBPartner(getCtx(), ship.getC_BPartner_ID(), get_TrxName());
        // Reference: Delivery: 12345 - 12.12.12
        MClient client = MClient.get(getCtx(), order.getAD_Client_ID());
        String AD_Language = client.getAD_Language();
        if (client.isMultiLingualDocument() && m_bp.getAD_Language() != null)
            AD_Language = m_bp.getAD_Language();
        if (AD_Language == null)
            AD_Language = Language.getBaseAD_Language();
        java.text.SimpleDateFormat format = DisplayType.getDateFormat(DisplayType.Date, Language.getLanguage(AD_Language));
        String reference = dt.getPrintName(m_bp.getAD_Language()) + ": " + ship.getDocumentNo() + " - " + format.format(ship.getMovementDate());
        m_ship = ship;
        // 
        MInvoiceLine line = new MInvoiceLine(m_invoice);
        line.setIsDescription(true);
        line.setDescription(reference);
        line.setLine(m_line + sLine.getLine() - 2);
        if (!line.save())
            throw new IllegalStateException("Could not create Invoice Comment Line (sh)");
        // Optional Ship Address if not Bill Address
        if (order.getBill_Location_ID() != ship.getC_BPartner_Location_ID()) {
            MLocation addr = MLocation.getBPLocation(getCtx(), ship.getC_BPartner_Location_ID(), null);
            line = new MInvoiceLine(m_invoice);
            line.setIsDescription(true);
            line.setDescription(addr.toString());
            line.setLine(m_line + sLine.getLine() - 1);
            if (!line.save())
                throw new IllegalStateException("Could not create Invoice Comment Line 2 (sh)");
        }
    }
    // 
    MInvoiceLine line = new MInvoiceLine(m_invoice);
    line.setShipLine(sLine);
    if (sLine.sameOrderLineUOM())
        line.setQtyEntered(sLine.getQtyEntered());
    else
        line.setQtyEntered(sLine.getMovementQty());
    line.setQtyInvoiced(sLine.getMovementQty());
    line.setLine(m_line + sLine.getLine());
    if (!line.save())
        throw new IllegalStateException("Could not create Invoice Line (s)");
    // Link
    sLine.setIsInvoiced(true);
    if (!sLine.save())
        throw new IllegalStateException("Could not update Shipment Line");
    log.fine(line.toString());
}
Also used : MDocType(org.compiere.model.MDocType) MInvoiceLine(org.compiere.model.MInvoiceLine) MInvoice(org.compiere.model.MInvoice) MBPartner(org.compiere.model.MBPartner) MLocation(org.compiere.model.MLocation) MClient(org.compiere.model.MClient)

Example 89 with MInvoice

use of org.compiere.model.MInvoice in project lar_361 by comitsrl.

the class LAR_Validator method changeVoidDocumentNo.

/**
 * Change DocumentNo in order to avoid modified sequence for given document
 */
// TODO - Improve and add this behavior to ADempiere and make it configurable (ideal)
private String changeVoidDocumentNo(final PO po) {
    final Properties ctx = po.getCtx();
    PO revPo = null;
    MSequence seq = null;
    // Corrije el nro de documento de la factura anulada y su reversa asociada
    if (po.get_TableName().equals(MInvoice.Table_Name)) {
        final MInvoice invoice = (MInvoice) po;
        // Si no se tiene la referencia a la reversión, no se procesa
        if (invoice.getReversal_ID() == 0)
            return null;
        revPo = new MInvoice(ctx, invoice.getReversal_ID(), invoice.get_TrxName());
        final MInvoice revInvoice = (MInvoice) revPo;
        log.info("Change DocumentNo of " + revInvoice);
        // Intenta recuperar la secuencia "definitiva". Si no tiene, intenta
        // recupera la secuencia "normal". Si no tiene, no sea hace nada debido
        // a que le documento NO tiene secuencia configurada
        int ad_Sequence_ID = invoice.getC_DocType().getDefiniteSequence_ID();
        if (ad_Sequence_ID == 0)
            ad_Sequence_ID = invoice.getC_DocType().getDocNoSequence_ID();
        if (ad_Sequence_ID != 0)
            seq = new MSequence(ctx, ad_Sequence_ID, invoice.get_TrxName());
        // Redefine los nros de documento y las descripciones de las facturas
        String revDocumentNo = "Rev-" + invoice.getDocumentNo() + "-" + invoice.getC_Invoice_ID();
        String voidDocumentNo = "Anu-" + invoice.getDocumentNo() + "-" + invoice.getC_Invoice_ID();
        revInvoice.setDocumentNo(revDocumentNo);
        revInvoice.setDescription("(" + voidDocumentNo + "<-)");
        invoice.setDocumentNo(voidDocumentNo);
        invoice.setDescription("(" + revDocumentNo + "<-)");
        // Si la secuencia es automática, retrocede la numeración
        if (seq != null && seq.isAutoSequence())
            seq.setCurrentNext(seq.getCurrentNext() - 1);
    }
    // Corrije el nro de documento del remito anulado y su reverso asociado
    if (po.get_TableName().equals(MInOut.Table_Name)) {
        final MInOut shipment = (MInOut) po;
        // Si no se tiene la referencia a la reversión, no se procesa
        if (shipment.getReversal_ID() == 0)
            return null;
        revPo = new MInOut(ctx, shipment.getReversal_ID(), shipment.get_TrxName());
        final MInOut revShipment = (MInOut) revPo;
        log.info("Change DocumentNo of " + revShipment);
        // Intenta recuperar la secuencia "definitiva". En caso que sea nula,
        // recupera la secuencia "normal"
        int AD_Sequence_ID = shipment.getC_DocType().getDefiniteSequence_ID();
        if (AD_Sequence_ID == 0)
            AD_Sequence_ID = shipment.getC_DocType().getDocNoSequence_ID();
        if (AD_Sequence_ID != 0)
            seq = new MSequence(ctx, AD_Sequence_ID, shipment.get_TrxName());
        String revDocumentNo = "Rev-" + shipment.getDocumentNo() + "-" + shipment.getM_InOut_ID();
        String voidDocumentNo = "Anu-" + shipment.getDocumentNo() + "-" + shipment.getM_InOut_ID();
        revShipment.setDocumentNo(revDocumentNo);
        revShipment.setDescription("(" + voidDocumentNo + "<-)");
        shipment.setDocumentNo(voidDocumentNo);
        shipment.setDescription("(" + revDocumentNo + "<-)");
        // Si encontró una secuencia, y la misma es automática, retrocede la numeración
        if (seq != null && seq.isAutoSequence())
            seq.setCurrentNext(seq.getCurrentNext() - 1);
    }
    // (siempre y cuando hayan cambiado y no sean nulos)
    if (revPo != null && !revPo.save())
        return "Error al guardar el documento inverso";
    if (po.is_Changed() && !po.save())
        return "Error al guardar el documento anulado";
    if (seq != null && seq.is_Changed() && !seq.save())
        return "Error al guardar la secuencia";
    return null;
}
Also used : MInOut(org.compiere.model.MInOut) MInvoice(org.compiere.model.MInvoice) Properties(java.util.Properties) MSequence(org.compiere.model.MSequence) PO(org.compiere.model.PO)

Example 90 with MInvoice

use of org.compiere.model.MInvoice in project lar_361 by comitsrl.

the class MLARPaymentHeader method completeIt.

@Override
public String completeIt() {
    log.info(toString());
    // Re-Check
    if (!m_justPrepared) {
        String status = prepareIt();
        if (!DocAction.STATUS_InProgress.equals(status))
            return status;
    }
    // Dispara la validación del documento
    m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_COMPLETE);
    if (m_processMsg != null)
        return DocAction.STATUS_Invalid;
    MPayment[] pays = getPayments(get_TrxName());
    int p = 0;
    for (; p < pays.length; p++) {
        pays[p].setDateAcct(getDateTrx());
        pays[p].setDateTrx(getCreated());
        pays[p].setTrxType(MPayment.TRXTYPE_CreditPayment);
        pays[p].processIt(ACTION_Complete);
        pays[p].save(get_TrxName());
        if (!DOCSTATUS_Completed.equals(pays[p].getDocStatus())) {
            m_processMsg = "@C_Payment_ID@: " + pays[p].getProcessMsg();
            return DocAction.STATUS_Invalid;
        }
    }
    // Asigna los cobros/pagos a las facturas
    MPaymentAllocate[] invoices = getInvoices(get_TrxName());
    if (invoices.length != 0) {
        p = 0;
        // Asignaciones
        for (int i = 0; (i < invoices.length && p < pays.length); ) {
            MAllocationHdr alloc = new MAllocationHdr(getCtx(), false, getDateTrx(), getC_Currency_ID(), "Asignación Pagos a Facturas - Cabecera: " + getDocumentNo(), get_TrxName());
            alloc.setAD_Org_ID(getAD_Org_ID());
            if (!alloc.save()) {
                log.severe("La Cabecera de Asignacion no pudo crearse");
                return DocAction.STATUS_Invalid;
            }
            MPaymentAllocate pa = invoices[i];
            MInvoice invoice = new MInvoice(Env.getCtx(), pa.getC_Invoice_ID(), get_TrxName());
            final BigDecimal impPago = pays[p].getPayAmt().add(pays[p].getWriteOffAmt()).subtract(pays[p].getAllocatedAmt().abs());
            final BigDecimal importeFactura = invoice.getOpenAmt().subtract(pa.getDiscountAmt());
            int comp = impPago.compareTo(importeFactura);
            MAllocationLine aLine = null;
            BigDecimal alineOUAmt = Env.ZERO;
            BigDecimal alineAmt;
            // Evita Sobrepagos
            if (comp <= 0)
                alineAmt = impPago;
            else
                alineAmt = importeFactura;
            alineOUAmt = importeFactura.subtract(impPago);
            if (isReceipt())
                aLine = new MAllocationLine(alloc, alineAmt, Env.ZERO, pa.getWriteOffAmt(), alineOUAmt);
            else
                aLine = new MAllocationLine(alloc, alineAmt.negate(), Env.ZERO, pa.getWriteOffAmt().negate(), alineOUAmt);
            aLine.setDocInfo(pa.getC_BPartner_ID(), 0, pa.getC_Invoice_ID());
            aLine.setPaymentInfo(pays[p].getC_Payment_ID(), 0);
            if (!aLine.save(get_TrxName()))
                log.warning("Asignación: No se pudo guradar la línea");
            else {
                pa.setC_AllocationLine_ID(aLine.getC_AllocationLine_ID());
                pa.saveEx();
            }
            if (comp >= 0) {
                i = i + 1;
                if (comp == 0)
                    p = p + 1;
            } else
                p = p + 1;
            // Cabecera de Asignación: Comienzo de WF
            alloc.processIt(DocAction.ACTION_Complete);
            alloc.save(get_TrxName());
            m_processMsg = "@C_AllocationHdr_ID@: " + alloc.getDocumentNo();
            log.fine(m_processMsg);
        }
    }
    // setC_BankAccount_ID(C_BankAccount_ID);
    // Dispara la validación del documento
    m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_COMPLETE);
    if (m_processMsg != null)
        return DocAction.STATUS_Invalid;
    // @mzuniga - Marca los cobros/pagos como asignados si corresponde
    for (p = 0; p < pays.length; p++) {
        pays[p].testAllocation();
        pays[p].saveEx();
    }
    setDocStatus(ACTION_Complete);
    setDocAction(DOCACTION_Close);
    setProcessed(true);
    // Marca los Certificados de Retención como Procesados
    if (!isReceipt()) {
        final MLARPaymentWithholding[] certificados = MLARPaymentWithholding.get(this);
        if (certificados.length > 0)
            for (final MLARPaymentWithholding c : certificados) c.setProcessed(true);
    }
    return DocAction.STATUS_Completed;
}
Also used : MPayment(org.compiere.model.MPayment) MInvoice(org.compiere.model.MInvoice) MAllocationLine(org.compiere.model.MAllocationLine) MPaymentAllocate(org.compiere.model.MPaymentAllocate) MAllocationHdr(org.compiere.model.MAllocationHdr) BigDecimal(java.math.BigDecimal)

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