Example #1
0
  /**
   * Descripción de Método
   *
   * @return
   * @throws Exception
   */
  protected String doIt() throws Exception {
    // JOptionPane.showMessageDialog( null,"En CopyFromOrder.doit() :=","-...Fin",
    // JOptionPane.INFORMATION_MESSAGE );
    int To_C_Order_ID = getRecord_ID();

    log.info("From C_Order_ID=" + p_C_Order_ID + " to " + To_C_Order_ID);

    if (To_C_Order_ID == 0) {
      throw new IllegalArgumentException("Target C_Order_ID == 0");
    }

    // Buscar el pedido de la factura
    MInvoice invoice = null;
    if (p_C_Invoice_ID != 0 && p_C_Order_ID == 0) {
      invoice = new MInvoice(getCtx(), p_C_Invoice_ID, get_TrxName());
      p_C_Order_ID = invoice.getC_Order_ID();
    }

    if (p_C_Order_ID == 0) {
      throw new IllegalArgumentException("Source C_Order_ID == 0");
    }

    MOrder from = new MOrder(getCtx(), p_C_Order_ID, get_TrxName());
    MOrder to = new MOrder(getCtx(), To_C_Order_ID, get_TrxName());

    // Si el tipo de documento del order from es un presupuesto vencido, hay
    // que verificar si a configuración del tipo de documento destino
    // permite crear a partir de presupuestos vencidos
    MDocType docTypeTo = new MDocType(getCtx(), to.getC_DocTypeTarget_ID(), get_TrxName());
    if (from.isExpiredProposal(Env.getDate()) && !docTypeTo.isAllowProposalDue()) {
      throw new Exception(Msg.getMsg(getCtx(), "NotAllowedProposalDue"));
    }

    // Copiar la cabecera si así lo requiere
    if (copyHeader) {
      // Datos a setear luego de la copia de campos
      Integer docTypeID = to.getC_DocTypeTarget_ID();
      String docAction = to.getDocAction();
      String docStatus = to.getDocStatus();
      PO.copyValues(from, to);
      to.setC_DocTypeTarget_ID(docTypeID);
      to.setDocStatus(docStatus);
      to.setDocAction(docAction);
      to.setProcessed(false);
      to.setRef_Order_ID(from.getC_Order_ID());
      if (!to.save()) {
        throw new Exception(CLogger.retrieveErrorAsString());
      }
    }

    int no = to.copyLinesFrom(from, false, false); // no Attributes

    //

    return "@Copied@=" + no;
  } // doIt
 /**
  * Este método es invocado cuando el usuario cambia la factura con pedido seleccionada en el
  * VLookup. Las subclases puede sobrescribir este comportamiento.
  *
  * @param invoiceID ID de la nueva factura seleccionada.
  */
 protected void invoiceOrderChanged(int invoiceID) {
   int relatedOrderID = 0;
   orderField.setValue(null);
   invoiceField.setValue(null);
   if (invoiceID > 0) {
     MInvoice invoice = new MInvoice(getCtx(), invoiceID, getTrxName());
     relatedOrderID = invoice.getC_Order_ID();
   }
   loadOrder(relatedOrderID, false);
   if (relatedOrderID > 0) {
     orderField.setValue(relatedOrderID);
   }
 }
 public void initializeCodeParts(MInvoice invoice, MDocType docType) {
   if (Util.isEmpty(getClientCuit(), true)) {
     getLog().severe("No existe CUIT de la compañia");
     return;
   }
   // b) Código de tipo de comprobante.
   if (Util.isEmpty(docType.getdocsubtypecae(), true)) {
     getLog().severe("No existe codigo de tipo de documento electronico");
     return;
   }
   setDocTypeCodeFE(docType.getdocsubtypecae());
   // c) Punto de venta.
   if (Util.isEmpty(invoice.getPuntoDeVenta(), true)) {
     getLog().severe("No existe punto de venta");
     return;
   }
   Integer puntoDeVenta = invoice.getPuntoDeVenta();
   String ptoVta = String.valueOf(puntoDeVenta);
   // El punto de venta debe ir con 0 cuando es menor a 1000
   if (puntoDeVenta < 1000) {
     ptoVta = "0";
     // Si es menor a 100, hay que agregar otro 0
     if (puntoDeVenta < 100) {
       ptoVta += "0";
     }
     // Si es menor a 10, hay que agregar otro 0
     if (puntoDeVenta < 10) {
       ptoVta += "0";
     }
     ptoVta = ptoVta + String.valueOf(puntoDeVenta);
   }
   setPuntoDeVenta(ptoVta);
   // d) Código de Autorización de Impresión (C.A.I.).
   // En realidad es el CAE lo que se debe imprimir
   if (Util.isEmpty(invoice.getcae(), true)) {
     getLog().severe("No existe CAE");
     return;
   }
   setCae(invoice.getcae());
   // e) Fecha de vencimiento.
   // Fecha de Vencimiento del CAE - Formato AAAAMMDD
   if (invoice.getvtocae() == null) {
     getLog().severe("No existe fecha de vencimieto de cae");
     return;
   }
   setCaeDueDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getvtocae()));
 }
  /**
   * Descripción de Método
   *
   * @return
   */
  protected void save() throws CreateFromSaveException {

    // La ubicación es obligatoria
    Integer locatorID = (Integer) locatorField.getValue();
    if (locatorID == null || (locatorID == 0)) {
      locatorField.setBackground(CompierePLAF.getFieldBackground_Error());
      throw new CreateFromSaveException("@NoLocator@");
    }

    // Actualiza el encabezado del remito (necesario para validaciones en las
    // líneas a crear del remito)
    MInOut inout = getInOut();
    log.config(inout + ", C_Locator_ID=" + locatorID);
    // Asocia el pedido
    if (p_order != null) {
      inout.setC_Order_ID(p_order.getC_Order_ID());
      inout.setDateOrdered(p_order.getDateOrdered());
      inout.setC_Project_ID(p_order.getC_Project_ID());
    }
    // Asocia la factura
    if ((m_invoice != null) && (m_invoice.getC_Invoice_ID() != 0)) {
      inout.setC_Invoice_ID(m_invoice.getC_Invoice_ID());
    }

    // Guarda el encabezado. Si hay error cancela la operación
    if (!inout.save()) {
      throw new CreateFromSaveException(CLogger.retrieveErrorAsString());
    }

    // Lines

    for (SourceEntity sourceEntity : getSelectedSourceEntities()) {
      DocumentLine docLine = (DocumentLine) sourceEntity;
      BigDecimal movementQty = docLine.remainingQty;
      int C_UOM_ID = docLine.uomID;
      int M_Product_ID = docLine.productID;

      // Crea la línea del remito

      MInOutLine iol = new MInOutLine(inout);
      iol.setM_Product_ID(M_Product_ID, C_UOM_ID); // Line UOM
      iol.setQty(movementQty); // Movement/Entered
      iol.setM_Locator_ID(locatorID); // Locator
      iol.setDescription(docLine.description);

      MInvoiceLine il = null;
      MOrderLine ol = null;

      // La línea del remito se crea a partir de una línea de pedido
      if (docLine.isOrderLine()) {
        OrderLine orderLine = (OrderLine) docLine;
        // Asocia línea remito -> línea pedido
        iol.setC_OrderLine_ID(orderLine.orderLineID);
        ol = new MOrderLine(Env.getCtx(), orderLine.orderLineID, getTrxName());
        // Proyecto
        iol.setC_Project_ID(ol.getC_Project_ID());
        if (ol.getQtyEntered().compareTo(ol.getQtyOrdered()) != 0) {
          iol.setMovementQty(
              movementQty
                  .multiply(ol.getQtyOrdered())
                  .divide(ol.getQtyEntered(), BigDecimal.ROUND_HALF_UP));
          iol.setC_UOM_ID(ol.getC_UOM_ID());
        }
        // Instancia de atributo
        if (ol.getM_AttributeSetInstance_ID() != 0) {
          iol.setM_AttributeSetInstance_ID(ol.getM_AttributeSetInstance_ID());
        }
        // Cargo (si no existe el artículo)
        if (M_Product_ID == 0 && ol.getC_Charge_ID() != 0) {
          iol.setC_Charge_ID(ol.getC_Charge_ID());
        }

        // La línea del remito se crea a partir de una línea de factura
      } else if (docLine.isInvoiceLine()) {
        InvoiceLine invoiceLine = (InvoiceLine) docLine;
        // Credit Memo - negative Qty
        if (m_invoice != null && m_invoice.isCreditMemo()) {
          movementQty = movementQty.negate();
        }
        il = new MInvoiceLine(Env.getCtx(), invoiceLine.invoiceLineID, getTrxName());
        // Proyecto
        iol.setC_Project_ID(il.getC_Project_ID());
        if (il.getQtyEntered().compareTo(il.getQtyInvoiced()) != 0) {
          iol.setQtyEntered(
              movementQty
                  .multiply(il.getQtyInvoiced())
                  .divide(il.getQtyEntered(), BigDecimal.ROUND_HALF_UP));
          iol.setC_UOM_ID(il.getC_UOM_ID());
        }
        // Cargo (si no existe el artículo)
        if (M_Product_ID == 0 && il.getC_Charge_ID() != 0) {
          iol.setC_Charge_ID(il.getC_Charge_ID());
        }
        // Si la línea de factura estaba relacionada con una línea de pedido
        // entonces se hace la asociación a la línea del remito. Esto es necesario
        // para que se actualicen los valores QtyOrdered y QtyReserved en el Storage
        // a la hora de completar el remito.
        if (invoiceLine.orderLineID > 0) {
          iol.setC_OrderLine_ID(invoiceLine.orderLineID);
        }
      }
      // Guarda la línea de remito
      if (!iol.save()) {
        throw new CreateFromSaveException(
            "@InOutLineSaveError@ (# "
                + docLine.lineNo
                + "):<br>"
                + CLogger.retrieveErrorAsString());

        // Create Invoice Line Link
      } else if (il != null) {
        il.setM_InOutLine_ID(iol.getM_InOutLine_ID());
        if (!il.save()) {
          throw new CreateFromSaveException(
              "@InvoiceLineSaveError@ (# "
                  + il.getLine()
                  + "):<br>"
                  + CLogger.retrieveErrorAsString());
        }
      }
    } // for all rows
  } // save
  /**
   * Descripción de Método
   *
   * @param C_Invoice_ID
   */
  private void loadInvoice(int C_Invoice_ID) {
    log.config("C_Invoice_ID=" + C_Invoice_ID);
    if (C_Invoice_ID > 0) {
      m_invoice = new MInvoice(Env.getCtx(), C_Invoice_ID, null); // save
      // Se carga la EC de la factura.
      if (bPartnerField != null) {
        bPartnerField.setValue(m_invoice.getC_BPartner_ID());
      }
    }
    p_order = null;

    List<InvoiceLine> data = new ArrayList<InvoiceLine>();

    StringBuffer sql = new StringBuffer();
    sql.append("SELECT ") // Entered UOM
        .append("l.C_InvoiceLine_ID, ")
        .append("l.Line, ")
        .append("l.Description, ")
        .append("l.M_Product_ID, ")
        .append("p.Name AS ProductName, ")
        .append("l.C_UOM_ID, ")
        .append("QtyInvoiced, ")
        .append("l.QtyInvoiced-SUM(NVL(mi.Qty,0)) AS RemainingQty, ")
        .append("l.QtyEntered/l.QtyInvoiced AS Multiplier, ")
        .append("COALESCE(l.C_OrderLine_ID,0) AS C_OrderLine_ID ")
        .append("FROM C_UOM uom, C_InvoiceLine l, M_Product p, M_MatchInv mi ")
        .append("WHERE l.C_UOM_ID=uom.C_UOM_ID ")
        .append("AND l.M_Product_ID=p.M_Product_ID ")
        .append("AND l.C_InvoiceLine_ID=mi.C_InvoiceLine_ID(+) ")
        .append("AND l.C_Invoice_ID=? ")
        .append(
            "GROUP BY l.QtyInvoiced, l.QtyEntered/l.QtyInvoiced, l.C_UOM_ID, l.M_Product_ID, p.Name, l.C_InvoiceLine_ID, l.Line, l.C_OrderLine_ID, l.Description ")
        .append("ORDER BY l.Line ");

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(sql.toString());
      pstmt.setInt(1, C_Invoice_ID);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        InvoiceLine invoiceLine = new InvoiceLine();

        // Por defecto no está seleccionada para ser procesada
        invoiceLine.selected = false;

        // ID de la línea de factura
        invoiceLine.invoiceLineID = rs.getInt("C_InvoiceLine_ID");

        // Nro de línea
        invoiceLine.lineNo = rs.getInt("Line");

        // Descripción
        invoiceLine.description = rs.getString("Description");

        // Cantidades
        BigDecimal multiplier = rs.getBigDecimal("Multiplier");
        BigDecimal qtyInvoiced = rs.getBigDecimal("QtyInvoiced").multiply(multiplier);
        BigDecimal remainingQty = rs.getBigDecimal("RemainingQty").multiply(multiplier);
        invoiceLine.lineQty = qtyInvoiced;
        invoiceLine.remainingQty = remainingQty;

        // Artículo
        invoiceLine.productID = rs.getInt("M_Product_ID");
        invoiceLine.productName = rs.getString("ProductName");

        // Unidad de Medida
        invoiceLine.uomID = rs.getInt("C_UOM_ID");
        invoiceLine.uomName = getUOMName(invoiceLine.uomID);

        // Línea de pedido (puede ser 0)
        invoiceLine.orderLineID = rs.getInt("C_OrderLine_ID");

        // Agrega la línea a la lista solo si tiene cantidad pendiente
        if (invoiceLine.remainingQty.compareTo(BigDecimal.ZERO) > 0) {
          data.add(invoiceLine);
        }
      }

    } catch (SQLException e) {
      log.log(Level.SEVERE, sql.toString(), e);
    } finally {
      try {
        if (rs != null) rs.close();
        if (pstmt != null) pstmt.close();
      } catch (Exception e) {
      }
    }

    loadTable(data);
  } // loadInvoice