XDocFromDocFrame.java :  » ERP-CRM-Financial » Evaristo-4.0 » com » m16e » mpbiz » docs » Java Open Source

Java Open Source » ERP CRM Financial » Evaristo 4.0 
Evaristo 4.0 » com » m16e » mpbiz » docs » XDocFromDocFrame.java
/*
 * XDocFromDocFrame.java
 */

package com.m16e.mpbiz.docs;

import com.m16e.mpbiz.common.MpBizAppConfig;
import com.m16e.mpbiz.common.MpBizAppContext;
import com.m16e.mpbiz.common.MpBizUser;
import com.m16e.mpbiz.common.bizclasses.MpBizDocStates;
import com.m16e.mpbiz.errors.MpBizError;
import com.m16e.mpbiz.i18n.MpBizBundle;
import com.m16e.mpbiz.listeners.DocListenerFactory;
import com.m16e.mpbiz.tables.DbDoc;
import com.m16e.mpbiz.tables.DbDocEstado;
import com.m16e.mpbiz.tables.DbDocLin;

import com.m16e.tools.MpAppContext;
import com.m16e.tools.MpAppGraphicsContext;
import com.m16e.tools.MpNameValuePair;
import com.m16e.tools.MpToolsException;
import com.m16e.tools.Tuple;
import com.m16e.tools.datamodels.ComboData;
import com.m16e.tools.datamodels.QueryData;
import com.m16e.tools.datamodels.XgmTableColDataModel;
import com.m16e.tools.datamodels.XgmTableDataModel;
import com.m16e.tools.datamodels.XgmTableModel;
import com.m16e.tools.db.Database;
import com.m16e.tools.db.DatabaseException;
import com.m16e.tools.db.DbTableInterface;
import com.m16e.tools.db.DbWorkingTable;
import com.m16e.tools.gui.GuiFactory;
import com.m16e.tools.i18n.LocaleBundle;
import com.m16e.tools.xgm.XgmAction;
import com.m16e.tools.xgm.XgmComponent;
import com.m16e.tools.xgm.XgmException;
import com.m16e.tools.xgm.XgmFactory;
import com.m16e.tools.xgm.XgmListener;
import com.m16e.tools.xgm.XgmRootContainer;
import com.m16e.tools.xgm.XgmTable;
import com.m16e.tools.xgm.XgmTextField;
import com.m16e.tools.xgm.event.XgmTableEvent;
import com.m16e.tools.xgm.listeners.XgmTableListener;
import com.m16e.tools.xml.XmlException;
import com.m16e.tools.xml.XmlTreeNodeable;

import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.print.PrinterException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.EventObject;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import org.apache.log4j.Logger;


///////////////////////////////////////////////////////////////
public class XDocFromDocFrame 
extends XDocFrame
implements XgmListener, MouseListener, KeyListener, XgmTableListener
{
  private static Logger logger = Logger.getLogger( XDocFromDocFrame.class );

  public static final String XGM_DOC = 
    "xgm-form-mp-doc-doc.xml";
  public static final String XGM_DOC_FRAME  = 
    "form-mp-doc-doc-frame";

  public static final String XGM_LIST_HELP_DOC = 
    "xgm-list-help-doc.xml";
  public static final String XGM_LIST_HELP_DOC_FRAME  = 
    "list-help-doc-frame";

  public static final String FLD_TAX_PERCENT = "tax_percent";
  
  public static final String FF_ORG_TIPO_ENT_ID = DbDocLin.FN_ORG_TIPO_ENT_ID;
  public static final String FF_ORG_TIPO_DOC_ID = DbDocLin.FIELDS[ DbDocLin.ORG_TIPO_DOC_ID ];  // org_tipo_doc_id 
  public static final String FF_ORG_DOC_ID = DbDocLin.FIELDS[ DbDocLin.ORG_DOC_ID ];        // org_doc_id 
//  public static final String FF_AUX_ITEM_ID = DbDocLin.FIELDS[ DbDocLin.AUX_ITEM_ID ];  // seller_id 
  public static final String FF_DESCRICAO = DbDocLin.FIELDS[ DbDocLin.DESCRICAO ];    
  public static final String FF_AUX_DOUBLE_1 = DbDocLin.FIELDS[ DbDocLin.AUX_DOUBLE_1 ];      
  public static final String FF_TOTAL_COM_TAXA = DbDocLin.FN_TOTAL_COM_TAXA;
//  public static final String FF_TAX_PERCENT = "tax_percent";
  public static final String FF_TOTAL_SEM_TAXA = DbDocLin.FIELDS[ DbDocLin.TOTAL_SEM_TAXA ];

  Integer idxColumnOrgTipoEntId = null;
  Integer idxColumnOrgTipoDocId = null;
  Integer idxColumnOrgDocId = null;
//  Integer idxColumnAuxItemId = null;
  Integer idxColumnDescricao = null;
  Integer idxColumnTotalComTaxa = null;
  Integer idxColumnTotalSemTaxa = null;

  Integer idxColumnAuxDouble1 = null;
//  Integer idxColumnTaxPercent = null;
  
  JPopupMenu docHelpMenu = new JPopupMenu();
  JMenuItem docHelpByDocOrg = null;
  
  ///////////////////////////////////////////////////////////////
  public XDocFromDocFrame() {}
  
  ///////////////////////////////////////////////////////////////
  public XDocFromDocFrame( XDocListener xDocListener )
  {
    super( xDocListener );
  }
  
  ///////////////////////////////////////////////////////////////
  public XDocFromDocFrame( 
    XDocListener xDocListener, MpBizDoc mpBizDoc, boolean initializaFrame ) 
  throws 
    SQLException, MpDocException, XgmException, DatabaseException, 
    MpToolsException, ParseException
  {
    super( xDocListener, mpBizDoc, initializaFrame  );
//    init();
  }
  
  ///////////////////////////////////////////////////////////////
  public XDocFromDocFrame( 
    XDocListener xDocListener, 
    Integer tipoEntId, Integer tipoDocId, Integer docId,
    String xgmDocFile ) //, boolean keepDocId ) 
  throws 
    SQLException, MpDocException, XgmException, DatabaseException, 
    MpToolsException, ParseException
  {
    super( xDocListener, tipoEntId, tipoDocId, docId, xgmDocFile ); 
//    init();
  }
  
  ///////////////////////////////////////////////////////////////
  @Override
  public void initFrame( 
    Integer tipoEntId, Integer tipoDocId, Integer docId,
    String xgmDocFile ) 
  throws SQLException, DatabaseException, MpDocException
  {
    if( xgmDocFile == null || xgmDocFile.length() == 0 )
    {
      MpBizAppConfig config = MpBizAppConfig.getInstance();
      xgmDocFile = config.getFormLayout( tipoEntId, tipoDocId );
    }
    setFormFile( xgmDocFile );
    try
    {
      if( mpBizDoc == null )
      {
        initializeBizDoc( tipoEntId, tipoDocId, docId ); //, keepDocId );
      }
      init();
    }
    catch( Exception e )
    {
      logger.error( e.getMessage(), e );
      throw new MpDocException(  e.getMessage() );
    }
  }
  
  ///////////////////////////////////////////////////////////////
  @Override
  public void initializeBizDoc( 
    Integer tipoEntId, Integer tipoDocId, Integer docId ) //, boolean keepDocId )
  throws SQLException, MpDocException, DatabaseException, MpToolsException
  {
    mpBizDoc = new MpBizDoc();
    if( docId.intValue() == 0 )
    {  // new doc
      mpBizDoc.setTipoEntId( tipoEntId );
      mpBizDoc.setTipoDocId( tipoDocId );
//      docTaxas = new MpBizDocTaxas();
      mpBizDoc.setEntId( 0 );
    }
    else
    {  // existing doc
      mpBizDoc = MpBizDoc.getById( tipoEntId, tipoDocId, docId );
      if( mpBizDoc == null )
        throw new MpDocException( 
          "Documento inexistente (" + tipoEntId + "," +
          tipoDocId + "," + docId );
      orgTipoEntId = tipoEntId;
      orgTipoDocId = tipoDocId;
      orgDocId = docId;
      mpBizDoc.setNewDoc( false ); 
      DbDoc orgDoc = new DbDoc();
      for( MpBizDocLin mdl : mpBizDoc.getDocLines() )
      {
        DbDocLin dl = mdl.getDocLin();
        orgDoc.setTipoEntId( dl.getOrgTipoEntId() );
        orgDoc.setTipoDocId( dl.getOrgTipoDocId() );
        orgDoc.setDocId( dl.getOrgDocId() );
        if( dl.getOrgTipoDocId() != null && dl.getOrgTipoDocId() != 0 )
        {
          if( !orgDoc.getById() )
            throw new MpDocException( "NO SUCH DOC: " + orgDoc );
          dl.setAuxDouble1( 
            orgDoc.getTotalComTaxas() - orgDoc.getAuxDouble1() + 
            dl.getTotalComTaxa() );
        }
      }
      locked = true;
    }
  }
  
  ///////////////////////////////////////////////////////////////
  @Override
  public void setEditable( boolean enable )
  {
    super.setEditable( enable );
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    int noCols = xtm.getColumnCount();
    java.util.List<Tuple> tuples = xtm.getData();
    for( Tuple t : tuples )
    {
      for( int f = 0; f < noCols; f++ )
      {
        XgmTableColDataModel xtcdm = xtm.getXgmTableColDataModel( f );
        boolean b = xtcdm.isEditable();
        b = b && enable;
        Boolean tEditable = t.isEditable( f );
        if( tEditable != null )
          b = b && tEditable;
        t.setEditable( f, b );
      }
    }
  }
  
  ////////////////////////////////////////////////////////////
  @Override
  public void setFormFromMpBizDoc()
  throws SQLException, MpDocException, XgmException, MpToolsException, DatabaseException
  {
    super.setFormFromMpBizDoc();
    docLinTable = (XgmTable) xgmDocFrame.getComponentByName( DOC_LIN_TABLE );
    
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    java.util.List<MpBizDocLin> docLins = mpBizDoc.getDocLines();
    if( docLins != null && docLins.size() > 0 )
    {
      int noCols = xtm.getColumnCount();
      //int noRows = docLins.size();
      java.util.List<Tuple> data = new ArrayList<Tuple>();
      for( MpBizDocLin mdl : docLins )
      {
        DbDocLin bean = mdl.getDocLin();
        Integer tipoEntId = bean.getOrgTipoEntId();
        Integer tipoDocId = bean.getOrgTipoDocId();
        Tuple newRow = new Tuple( noCols );
        if( tipoDocId != null )
        {
          for( int g = 0; g < noCols; g++ )
          {
            if( g == idxColumnOrgTipoEntId )
            {
              newRow.set(
                g,
                new ComboData( 
                  tipoEntId, 
                  MpDocFactory.getInstance().getTipoEntName( tipoEntId ) ) );
            }
            if( g == idxColumnOrgTipoDocId )
            {
              newRow.set(
                g,
                new ComboData( 
                  tipoDocId, 
                  MpDocFactory.getInstance().getTipoDocName( tipoDocId ) ) );
            }
            else if( g == idxColumnOrgDocId )
            {
              newRow.set( g, bean.getOrgDocId() );
            }
  //          else if( g == idxColumnAuxItemId )
  //          {
  //            newRow.set( g, bean.getAuxItemId() );
  //          }
            else if( g == idxColumnDescricao )
            {
              newRow.set( g, bean.getDescricao() );
            }
            else if( g == idxColumnTotalComTaxa )
            {
              newRow.set( g, bean.getTotalComTaxa() );
            }
            else if( g == idxColumnTotalSemTaxa )
            {
              newRow.set( g, bean.getTotalSemTaxa() );
            }
            else if( g == idxColumnAuxDouble1 )
            {
              newRow.set( g, bean.getAuxDouble1() );
            }
          }
        }
        data.add( newRow );
      }
      xtm.setData( data );
    }
    else
    {
      xtm.add( xtm.getEmptyTuple() );
      int tipoDocId = MpDocFactory.TDOC_INVOICE;
      xtm.setValueAt( 
        new ComboData( tipoDocId, MpDocFactory.getInstance().getTipoDocName( tipoDocId ) ), 
        0, idxColumnOrgTipoDocId, false );
    }
    xtm.addTableListener( this );
    //tEdit.addTEditListener( this );
    //docLinTable.setXgmTableModel( xtm );
    XgmTextField btfTotalDoc = 
      (XgmTextField) docPanel.getComponentByName( 
        DbDoc.FIELDS[ DbDoc.TOTAL_COM_TAXAS ] );
    mpBizDoc.computeTotal();
    Double totalComTaxas = mpBizDoc.getDoc().getTotalComTaxas();
    btfTotalDoc.setComponentValueFromObject( totalComTaxas );
    
    XgmTable docPagTable = getDocPagTable();
    if( docPagTable != null )
    {
      updatePayTable();
    }
    docLinTable.getSwingComponent().invalidate();
    docPanel.getSwingContainer().invalidate();
    if( locked )
    {
      docLinTable.setEditable( false );
      if( docPagTable != null )
      {
        docPagTable.setEditable( false );
      }
    }
    else
    {
      docLinTable.setEditable( true );
      if( docPagTable != null )
      {
        docPagTable.setEditable( true );
      }
    }
  }
  
//  ////////////////////////////////////////////////////////////
//  private void updateTotals()
//  throws MpDocException, MpToolsException, SQLException, ParseException, XgmException
//  {
//    Double total = mpBizDoc.getDoc().getTotalComTaxas();
//    if( xDocListener != null )
//    {
//      xDocListener.processDocEvent( 
//        new MpBizDocEvent( MpBizDocEvent.DOC_TOTALS, total ) );
//    }
//    docPanel.getSwingContainer().invalidate();
//    updatePag();
//  }
//  
//  ////////////////////////////////////////////////////////////
//  private void updatePag()
//  throws MpDocException, MpToolsException, SQLException, ParseException, XgmException
//  {
////    setMpBizDocFromForm();
////    MpBizErrorList errList = computeTotal( true, false );
//    Double total = mpBizDoc.getDoc().getTotalComTaxas();
////    Double total = new Double( computeTotal( false, false ) );
//    docPagTable = getDocPagTable();
//    if( docPagTable != null )
//    {
//      XgmTableModel xtm = docPagTable.getXgmTableModel();
//      int nRows = xtm.getRowCount();
//      if( nRows == 0 )
//      {
//        xtm.add();
//        nRows = xtm.getRowCount();
//      }
//      
//      if( nRows == 1 )
//      {
//        int idx = xtm.getColumnIndex( DbDocPag.FN_VALOR );
//        Object o = xtm.getValueAt( 0, idx );
//        if( o instanceof Double )
//        {
//          xtm.setValueAt( total, 0, idx );
//        }
//        docPagTable.getSwingComponent().invalidate();
//        docPagTable.getSwingComponent().repaint();
//      }
//    }
//  }
//  
  ////////////////////////////////////////////////////////////
  protected void addListenersToDocLinTable()
  {
    docLinTable.getTable().addMouseListener( this );
    docLinTable.getTable().addKeyListener( this );
    docLinTable.getTable().changeSelection( 0, 0, false, false );
    docLinTable.getXgmTableModel().setAllowedToAppendLines( true );
    docLinTable.getXgmTableModel().setAllowedToRemoveLines( true );
  }
  
  ////////////////////////////////////////////////////////////
  @Override
  protected void init()
  throws 
    SQLException, MpDocException, DatabaseException
  {
    super.init();
//    xgmDocFrame.refreshComponentValue();
    docLinTable = (XgmTable) xgmDocFrame.getComponentByName( DOC_LIN_TABLE );
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    
    idxColumnOrgTipoEntId = xtm.getColumnIndex( FF_ORG_TIPO_ENT_ID );
    idxColumnOrgTipoDocId = xtm.getColumnIndex( FF_ORG_TIPO_DOC_ID );
    idxColumnOrgDocId = xtm.getColumnIndex( FF_ORG_DOC_ID );
//    idxColumnAuxItemId = xtm.getColumnIndex( FF_AUX_ITEM_ID );
    idxColumnDescricao = xtm.getColumnIndex( FF_DESCRICAO );
    idxColumnTotalComTaxa = xtm.getColumnIndex( FF_TOTAL_COM_TAXA );
    idxColumnTotalSemTaxa = xtm.getColumnIndex( FF_TOTAL_SEM_TAXA  );

    idxColumnAuxDouble1 = xtm.getColumnIndex( FF_AUX_DOUBLE_1 );
//    idxColumnTaxPercent = xtm.getColumnIndex( FF_TAX_PERCENT );
  
    docLinTable.addXgmListener( this );
    docLinTable.setSortable( false );
    mpBizDoc.setNeedsRecalc( true );
    try
    {
      setFormFromMpBizDoc();
      refreshComponentValue();
      if( docLinTable != null )
      {
        docLinTable.setSortable( false );
        docLinTable.getTable().addMouseListener( this );
        docLinTable.getTable().addKeyListener( this );
        xtm.setAllowedToAppendLines( true );
        xtm.setAllowedToRemoveLines( true );
        xtm.addTableListener( this );
      }

      addListenersToDocLinTable();

      int id = mpBizDoc.getTipoDocId().intValue();
      XgmTable docPagTable = getDocPagTable();
      if( docPagTable != null )
      {
        docPagTable.setSortable( false );
        if( docPagTable.getXgmTableModel().getRowCount() > 0 )
          docPagTable.getTable().changeSelection( 0, 0, false, false );
        docPagTable.getXgmTableModel().setAllowedToAppendLines( true );
        docPagTable.getXgmTableModel().setAllowedToRemoveLines( true );
      }
      if( !mpBizDoc.isNewDoc() )
        updateTotals();
      initDocLinMenus();
    }
    catch( Exception e )
    {
      logger.error( e.getMessage(), e );
      throw new MpDocException( e.getMessage() );
    }
    docPanel.getSwingContainer().repaint();
  }
  

  ///////////////////////////////////////////////////////////
  public void showDocHelpMenu( Component c, int x, int y )
  {
    docHelpMenu.show( c, x, y );
  }
  
  ////////////////////////////////////////////////////////////
  public void helpDoc( QueryData where, String order )
  {
    try
    {
      String layout = XGM_LIST_HELP_DOC;
      XgmRootContainer xFrame = new XgmRootContainer( this );
      xFrame.setLayout( layout, true, XgmFactory.TAG_PREFIX + XgmTable.TAG_TABLE );
      
      xFrame.setLocale( MpAppContext.getInstance().getLocale() );

      XgmTable xt = (XgmTable) xFrame.getComponentByTagName( XgmTable.TAG_TABLE );
      XgmTableDataModel xtdm = xt.getXgmTableDataModel();
      xtdm.setWhereClause( where );
      xtdm.setOrderBy( order );
      xtdm.requery();
      //xFrame.addWindowListener( this );
      //xFrame.setVisible( true );;
    }
    catch( Exception e )
    {
      String msg = e.getMessage();
      logger.error( e.getMessage(), e );
      JOptionPane.showMessageDialog( xgmDocFrame.getSwingContainer(), msg );
    }
  }

  ////////////////////////////////////////////////////////////
  protected void initDocLinMenus() 
  throws SQLException
  {
    final Database database = MpAppContext.getInstance().getDatabase();
    // prod by doc org
    Action docHelpByDocOrgAction =
      new AbstractAction( "Documentos em Aberto" )
      {
        public void actionPerformed( ActionEvent e )
        {
          String where =
            database.getSqlFieldName( 
              DbDoc.FIELDS[ DbDoc.ENT_ID ] ) +
            "=" + mpBizDoc.getEntId() + 
            " and " +
            database.getSqlFieldName( 
              DbDoc.FIELDS[ DbDoc.DOC_ID ] ) +
            " > 0" + 
            " and " +
            database.getSqlFieldName( 
              DbDoc.FIELDS[ DbDoc.TIPO_ENT_ID ] ) +
            "=" + mpBizDoc.getTipoEntId() + 
            " and (" +
              database.getSqlFieldName( 
                DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] ) +
              "=" + MpDocFactory.TDOC_INVOICE + 
              " or " +
              database.getSqlFieldName( 
                DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] ) +
              "=" + MpDocFactory.TDOC_CREDIT_NOTE + 
              " or " +
              database.getSqlFieldName( 
                DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] ) +
              "=" + MpDocFactory.TDOC_DEBIT_NOTE + 
            ") and " +
            DbDocEstado.T_NAME + "." +
            DbDocEstado.FN_TIPO_ESTADO_ID + " = " +
            MpBizDocStates.DocStateType.TRACKING.getCode() + " and " +
            DbDocEstado.T_NAME + "." + 
            DbDocEstado.FIELDS[ DbDocEstado.ESTADO_ID ] + 
            " < 999";
          String order =
            database.getSqlFieldName( 
              DbDoc.FIELDS[ DbDoc.DATA_DOC ] );
          helpDoc( new QueryData( where ), order );
        }
      }; 
    docHelpByDocOrg = new JMenuItem( docHelpByDocOrgAction );
    Font menuFont = MpAppGraphicsContext.getInstance().getDefaultFont();
    docHelpByDocOrg.setFont( menuFont );
    docHelpMenu.add( docHelpByDocOrg );
  }
  
  ///////////////////////////////////////////////////////////
  // interface KeyListener: BEGIN
  ///////////////////////////////////////////////////////////
  public void keyPressed( KeyEvent e ) {}
  public void keyTyped( KeyEvent e ) {}
  
  ///////////////////////////////////////////////////////////
  public void keyReleased( KeyEvent e )
  {
    Component comp = e.getComponent();
    if ( e.getKeyCode() == MpBizAppContext.getInstance().getFillHelpKey() && !locked )
    {
      if ( comp instanceof JTable )
      {
        JTable table = (JTable) comp;
        Point point = new Point( comp.getX(), comp.getY() );
        currentRow = table.getSelectedRow();
        int idx = table.columnAtPoint( point );
        if( idx == idxColumnOrgTipoDocId || idx == idxColumnOrgDocId )
          showDocHelpMenu( table, (int) point.getX(), (int) point.getY() );
      }
    }
  }
  
  ///////////////////////////////////////////////////////////
  // interface KeyListener: END
  ///////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////
  // interface MouseListener: BEGIN
  ///////////////////////////////////////////////////////////
  public void mousePressed( MouseEvent e )
  {
  }

  ///////////////////////////////////////////////////////////
  public void mouseReleased( MouseEvent e )
  {
    if( e.getButton() == MouseEvent.BUTTON3 && !locked )
    {
      Component c = (Component) e.getSource();
      if ( c instanceof JTable )
      {
        if( mpBizDoc.isClosed() )
          return;
        
        JTable table = (JTable) c;
        //Point point = new Point( e.getX(), e.getY() );
        Point point = new Point( c.getX(), c.getY() );
        
        int col = table.columnAtPoint( point );
        currentRow = table.rowAtPoint( point );
        if( col == idxColumnOrgTipoEntId || col == idxColumnOrgTipoDocId ||
            col == idxColumnOrgDocId )
          showDocHelpMenu(
            table,
            docLinTable.getSwingComponent().getX() + e.getX(), 
            docLinTable.getSwingComponent().getY() + table.getRowHeight() + e.getY() );
      }
      else
        super.mouseReleased( e );
    }
  }

  ////////////////////////////////////////////////////////////
  @Override
  public void mouseEntered( MouseEvent e )
  {
  }
  
  ////////////////////////////////////////////////////////////
  @Override
  public void mouseClicked( MouseEvent e )
  {
  }
  
  ////////////////////////////////////////////////////////////
  @Override
  public void mouseExited( MouseEvent e )
  {
  }
  
  ///////////////////////////////////////////////////////////
  // interface MouseListener: END
  ///////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////
  private void processHelpDoc(
    java.util.List<XmlTreeNodeable> selected, DbTableInterface tab )
  throws 
    SQLException, MpDocException, MpToolsException, XgmException, ParseException, 
    DatabaseException
  {
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    int maxRows = xtm.getMaxRows();
    currentRow = docLinTable.getTable().getSelectedRow();
    if( currentRow < 0 )
      currentRow = xtm.getRowCount() - 1;
    int noRows = currentRow - 1;
    if( maxRows > 0 && noRows + selected.size() >= maxRows - 1 )
    {
      MessageFormat messageFormat = new MessageFormat("");
      Object[] msgArgs = { new Integer( maxRows ) };
      String pattern = 
        LocaleBundle.getInstance().getBundleMessage( LocaleBundle.MSG_MAX_LINES_REACHED );
      messageFormat.applyPattern( pattern );

      throw new MpDocException( messageFormat.format( msgArgs ) );
    }
    for( int f = 0; f < selected.size(); f++ )
    {
      tab.setData( selected.get( f ) );
      if ( tab instanceof DbDoc )
      {
        DbDoc dbDoc = (DbDoc) tab;
        if( !dbDoc.getById() )
          throw new MpDocException( "NO SUCH DOC: " + dbDoc );
        if( f > 0 )
        {
          xtm.add();
        }
        Integer orgTipoEntIdNew = dbDoc.getTipoEntId();
        String sTEnt =
          MpDocFactory.getInstance().getDocName(
            dbDoc.getTipoEntId(), orgTipoEntIdNew );
        ComboData cdTEnt = 
          new ComboData( orgTipoEntIdNew.intValue(), sTEnt );
        xtm.setValueAt( cdTEnt, currentRow + f, idxColumnOrgTipoEntId, false );
        
        Integer orgTipoDocIdNew = dbDoc.getTipoDocId();
        String sTDoc =
          MpDocFactory.getInstance().getDocName(
            dbDoc.getTipoEntId(), orgTipoDocIdNew );
        ComboData cdTDoc = 
          new ComboData( orgTipoDocIdNew.intValue(), sTDoc );
        xtm.setValueAt( cdTDoc, currentRow + f, idxColumnOrgTipoDocId, false );

        Integer docId = dbDoc.getDocId();
        xtm.setValueAt( docId, currentRow + f, idxColumnOrgDocId, false );
        String sDocId = null;
        if( mpBizDoc.getTipoEntId() == MpDocFactory.TENT_CUSTOMER )
          sDocId = "" + docId;
        else if( mpBizDoc.getTipoEntId() == MpDocFactory.TENT_SUPPLIER )
        {
          sDocId = dbDoc.getCodExtDoc();
        }
        String description = 
          sTDoc + " " +
          LocaleBundle.getInstance().getBundleMessage( LocaleBundle.MSG_ABREVIATED_NUMBER ) +
          " " + sDocId;
        xtm.setValueAt( description, currentRow + f, idxColumnDescricao, false );

        Double totalToPay = dbDoc.getTotalComTaxas() - dbDoc.getAuxDouble1();
        xtm.setValueAt( totalToPay, currentRow + f, idxColumnTotalComTaxa, false  );

        Double auxDouble1 = dbDoc.getAuxDouble1();
        if( auxDouble1 == null )
          auxDouble1 = 0.0;
        xtm.setValueAt( 
          totalToPay, 
          currentRow + f, idxColumnAuxDouble1, false );
        
        Double totalSemTaxas = dbDoc.getTotalSemTaxas();
        xtm.setValueAt( 
          totalSemTaxas, 
          currentRow + f, idxColumnTotalSemTaxa, false );
        
        XgmTextField btfTotalDoc = 
          (XgmTextField) docPanel.getComponentByName( 
          DbDoc.FIELDS[ DbDoc.TOTAL_COM_TAXAS ] );
        setMpBizDocFromForm();
        Double total = mpBizDoc.getDoc().getTotalComTaxas();
        btfTotalDoc.setComponentValueFromObject( total );
      }
    }
    validateDocument( false );
    updatePayTable();
    xgmDocFrame.getSwingContainer().repaint();
  }
  
  ///////////////////////////////////////////////////////////
  @Override
  public boolean processListTab( 
    EventObject eo, XgmComponent component, XmlTreeNodeable xtnResult, 
    DbTableInterface tab ) 
  throws 
    XmlException, PrinterException, XgmException, SQLException,
    FileNotFoundException, MpToolsException, IOException, DatabaseException 
  {
    boolean done = false;
    String action = xtnResult.getAttribute( XgmAction.ATTRIB_ACTION_NAME );
    XgmRootContainer xrc = component.getXgmContainer().getRootContainer();
    if ( action.length() > 0 )
    {
      if( action.equals( XgmAction.ACT_CANCEL ) )
      {
        done = true;
        xrc.dispose();
      }
      else if ( action.equals( XgmAction.ACT_CLOSE ) )
      {
        done = true;
        XmlTreeNodeable xtnTable = 
          xtnResult.getChildByTagName( true, XgmTable.TAG_TABLE );
        XmlTreeNodeable xtnData = 
          xtnTable.getChildByTagName( false, DbWorkingTable.TAG_DATA );
        
        java.util.List<XmlTreeNodeable> vRows = 
          xtnData.getChildrenByTagName( DbWorkingTable.TAG_ROW );

        java.util.List<XmlTreeNodeable> vSelected = new ArrayList<XmlTreeNodeable>();
        if( vRows != null )
          vSelected = XgmFactory.getSelectedRows( vRows );

        if( vSelected.size() == 0 )
        {
          JOptionPane.showMessageDialog( 
            xrc.getSwingContainer(), 
            LocaleBundle.getInstance().getBundleMessage( 
              LocaleBundle.MSG_MUST_SELECT_LINE ) );
        }
        else
        {
          try
          {
            if( tab instanceof DbDoc )
            {
              processHelpDoc( vSelected, tab );
            }
            else
            {
              JOptionPane.showMessageDialog( 
                xrc.getSwingContainer(), "Tabela desconhecida (" + 
                tab.getClass().getName() + ")" );
            }
            xrc.dispose();
            //inHelp = false;
          }
          catch( Exception e )
          {
            logger.error( e.getMessage(), e );
            JOptionPane.showMessageDialog( xrc.getSwingContainer(), e.getMessage() );
          }
        }
      }
    }
    if( !done )
      done = super.processListTab( eo, component, xtnResult, tab );
    return done;
  }

//  ///////////////////////////////////////////////////////////
//  @Override
//  public void computeTotal()
//  throws MpDocException, SQLException, DatabaseException
//  {
//    mpBizDoc.validateDocument( false );
//    showDocErrors();
//  }
//
//  ////////////////////////////////////////////////////////////
//  @Override
//  public void validateDocument( boolean create )
//  throws MpDocException
//  {
//    try
//    {
//      validateDate();
//      DbDoc dbDoc = new DbDoc();
//      dbDoc.setTipoEntId( mpBizDoc.getTipoEntId() );
//
//      MpBizEnt mpBizEnt = mpBizDoc.getBizEnt();
//      XgmTextField btf =
//        (XgmTextField) docPanel.getComponentByName(
//          dbDoc.getField( DbDoc.ENT_ID ).getFieldName() );
//      Integer entId = (Integer) btf.getComponentValue();
//      if ( !mpBizEnt.getById( entId ) )
//        throw new MpDocException(
//          "Entidade desconhecida (" + entId + ")" );
//
//      java.util.List<Tuple> docLines = docLinTable.getXgmTableModel().getData();
//      for( Tuple t : docLines )
//      {
//        ComboData cd = (ComboData) t.get( idxColumnOrgTipoDocId );
//        if( cd != null )
//        {
//          Integer tipoDocId = cd.getCode();
//          Integer docId = (Integer) t.get( idxColumnOrgDocId );
//          if( docId.intValue() > 0 )
//          {
//            dbDoc.setTipoDocId( tipoDocId );
//            dbDoc.setDocId( docId );
//            if ( !dbDoc.getById() )
//            {
//              throw new MpDocException(
//                "Documento desconhecido (" + dbDoc.getTipoEntId() + ", " +
//                dbDoc.getTipoDocId() + ", " + dbDoc.getDocId() + ")!" );
//            }
//          }
//        }
//      }
//    }
//    catch( Exception e )
//    {
//      logger.error( e.getMessage(), e );
//      throw new MpDocException( e.getMessage() );
//    }
//  }
//
//  ////////////////////////////////////////////////////////////
//  public MpBizDocActionResult saveDocument() 
//  throws MpDocException
//  {
//    MpBizDocActionResult mbdar = null;
//    Database database = null;
//    int docId = 0;
//    XgmPanel docPanel =
//      (XgmPanel) xgmDocFrame.getComponentByName( DOC_PANEL );
//    XgmTable docLinTable =
//      (XgmTable) xgmDocFrame.getComponentByName( DOC_LIN_TABLE );
//    boolean success = false;
//    try
//    {
//      database = MpAppContext.getInstance().getDatabase();
//      database = MpAppContext.getInstance().getDatabase();
//      setMpBizDocFromForm();
//      int id = mpBizDoc.getTipoDocId().intValue();
//      database.beginTransaction();
//      if( mpBizDoc.isNewDoc() )
//        mpBizDoc.setDraft( true );
//      mbdar = mpBizDoc.updateDocument();
//      //con.commit();
//      
//      if( xDocListener != null && !isPreviewing )
//        xDocListener.docCreated( 
//          mpBizDoc.getTipoEntId(), mpBizDoc.getDocId(), mpBizDoc.getDocId(), auxData );
//      database.commitTransaction();
//      success = true;
//      
//    }
//    catch( Exception e )
//    {
//      logger.error( e.getMessage(), e );
//      throw new MpDocException( e.getMessage(), MpDocException.SQL_ERROR );
//    }
//    finally
//    {
//      try {
//        if( !success ) database.rollbackTransaction();
//      } catch( SQLException sqle2 ) { sqle2.printStackTrace(); }
//    }
//    return mbdar;
//  }
//
  ////////////////////////////////////////////////////////////
  public void setMpBizDocLineFromForm( int line ) 
  throws SQLException
  {
    docLinTable = (XgmTable) xgmDocFrame.getComponentByName( DOC_LIN_TABLE );
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    
    Tuple row = xtm.getRow( line );
    MpBizDocLin bizDocLin = mpBizDoc.getNewDocLin();
    DbDocLin docLin = bizDocLin.getDocLin();
    Object oAux = null;
    for( int f = 0; f < row.size(); f++ )
    {
      oAux = row.get( f );
      if( f == idxColumnOrgTipoEntId )
      {
        if( oAux instanceof ComboData  )
        {
          docLin.setOrgTipoEntId( new Integer( ((ComboData) oAux).getCode() ) );
        }
      }
      else if( f == idxColumnOrgTipoDocId )
      {
        if( oAux instanceof ComboData  )
        {
          docLin.setOrgTipoDocId( new Integer( ((ComboData) oAux).getCode() ) );
        }
      }
      else if( f == idxColumnOrgDocId )
      {
        docLin.setOrgDocId( (Integer) oAux);
      }
//      else if( f == idxColumnAuxItemId )
//      {
//        docLin.setAuxItemId( (Integer) oAux);
//      }
      else if( f == idxColumnDescricao )
      {
        docLin.setDescricao( (String) oAux);
      }
      else if( f == idxColumnAuxDouble1 )
      {
        if( oAux == null )
          oAux = "0";
        docLin.setAuxDouble1( new Double( oAux.toString() ) );
      }
      else if( f == idxColumnTotalComTaxa )
      {
        if( oAux == null )
          oAux = "0";
        docLin.setTotalComTaxa( new Double( oAux.toString() ) );
      }
      else if( f == idxColumnTotalSemTaxa )
      {
        if( oAux == null )
          oAux = "0";
        docLin.setTotalSemTaxa( new Double( oAux.toString() ) );
      }
    }
    mpBizDoc.setDocLine( line, bizDocLin );
  }
  
  ////////////////////////////////////////////////////////////
  @Override
  public void setMpBizDocFromForm()
  throws SQLException, MpToolsException, XgmException, DatabaseException
  {
    super.setMpBizDocFromForm();
    docLinTable = (XgmTable) xgmDocFrame.getComponentByName( DOC_LIN_TABLE );
    XgmTableModel xtm = docLinTable.getXgmTableModel();
    int nRows = xtm.getRowCount();
    for( int f = 0; f < nRows; f++ )
    {
      setMpBizDocLineFromForm( f );
    }
    mpBizDoc.setNeedsRecalc( true );
  }

//  ///////////////////////////////////////////////////////////
//  // interface XgmListener: BEGIN
//  ///////////////////////////////////////////////////////////
//  public DbTableInterface getTableByName( String tableName )
//    throws SQLException
//  {
//    return MpBizAppContext.getInstance().getTableByName( tableName );
//  }
//  
//  ////////////////////////////////////////////////////////////
//  public Locale getCurrencyLocale( Object currency )
//    throws SQLException
//  {
//    return mpBizFactory.getCurrencyLocale( currency );
//  }
//  
//  ////////////////////////////////////////////////////////////
//  public String getCurrencyAttributeName()
//  {
//    return MpBizAppContext.getInstance().getMpBiz().getCurrencyAttributeName();
//  }
//  
  ///////////////////////////////////////////////////////////
  @Override
  public boolean processResult( 
    EventObject eo, XgmComponent component, String actionObjet, 
    XmlTreeNodeable xtnResult, java.util.List<MpNameValuePair> options )
  {
    boolean done = false;
    if( xtnResult == null )
      return true;
    String action = xtnResult.getAttribute( XgmAction.ATTRIB_ACTION_NAME );
    
    if( logger.isInfoEnabled() )
    {
      logger.info( "action: " + action );
    }
    if( logger.isDebugEnabled() )
    {
      logger.debug( "result:\n" + xtnResult.toXml( 1 ) );
    }
    XgmRootContainer xrc = component.getXgmContainer().getRootContainer();
    GuiFactory.clearMsg( xrc );
    XmlTreeNodeable xtnXrc = 
      xtnResult.getChildByTagName( false, XgmRootContainer.TAG_XGM_CONTAINER );
    String containerName = xtnXrc.getAttribute( XgmComponent.NAME );
    
    done = 
      DocListenerFactory.processResult( 
        this, eo, component, actionObjet, xtnResult, options );
    if( done )
      return done;
    
    // doc
    if( containerName.equals( XGM_LIST_HELP_DOC_FRAME ) )
    {
      done = true;
      try
      {
        DbDoc dbDoc = new DbDoc();
        processListTab( eo, component, xtnResult, dbDoc );
      }
      catch( Exception e )
      {
        logger.error( e.getMessage(), e );
        GuiFactory.showErrorMsg( component, e );
      }
    }
    // this
    else if( containerName.equals( XGM_DOC_FRAME ) )
    {
      if( action.equals( BUTTON_NEW ) )
      {
        done = true;
        boolean success = false;
        try
        {
//          validateDocument( true );
          setMpBizDocFromForm();
          success = createDocument();
          if( success )
            printDoc();
        }
        catch( Exception e )
        {
          logger.error( e.getMessage(), e );
          GuiFactory.showErrorMsg( component, e );
        }
      }
      else if( action.equals( BUTTON_PREVIEW ) )
      {
        done = true;
        try
        {
//          validateDocument( true );
          if( mpBizDoc.isNewDoc() )
            previewDocument();
          else
            printDoc();
        }
        catch( Exception e )
        {
          logger.error( e.getMessage(), e );
          GuiFactory.showErrorMsg( component, e );
        }
      }
      else if( action.equals( BUTTON_SAVE ) )
      {
        done = true;
        Database database = null;
        try
        {
//          validateDocument( false );
//          setMpBizDocFromForm();
          if( saveDocument().getSucceded() )
            printDoc();
          xgmDocFrame.dispose();
        }
        catch( Exception e )
        {
          logger.error( e.getMessage(), e );
          GuiFactory.showErrorMsg( component, e );
        }
      }
      else if( action.equals( BUTTON_DEL ) )
      {
        done = true;
        int op =
          JOptionPane.showConfirmDialog(
            xgmDocFrame.getSwingContainer(), 
            MpBizBundle.getInstance().getBundleMessage( 
              MpBizBundle.MSG_CONFIRM_DEL_TMP_DOC ) );
        if( op == JOptionPane.YES_OPTION )
        {
          try
          {
//            validateDocument( true );
            try
            {
              deleteDocument();
//              mpBizDoc.deleteDoc( false );
            }
            catch( MpDocException e )
            {
              if( e.getErrorCode() == MpDocException.HAS_FOLLOWING_DOCS &&
                  MpBizUser.getInstance().isAdmin() )
              {
                op =
                  JOptionPane.showConfirmDialog(
                    xgmDocFrame.getSwingContainer(), 
                    "Confirma APAGAR documento?" );
                if( op == JOptionPane.YES_OPTION )
                {
                  deleteDocument( true );
//                  mpBizDoc.deleteDoc( true );
                }
              }
            }
            xgmDocFrame.dispose();
          }
          catch( Exception e )
          {
            logger.error( e.getMessage(), e );
            JOptionPane.showMessageDialog( xgmDocFrame.getSwingComponent(), e.getMessage() );
          }
        }
        xgmDocFrame.dispose();
      }
      else if ( action.equals( BUTTON_CANCEL ) )
      {
        done = true;
        xgmDocFrame.dispose();
      }
    }
    if( !done )
      done = super.processResult(  eo, component, actionObjet, xtnResult, options );
    return done;
  }
  
  ////////////////////////////////////////////////////////////
  // WindowListener: BEGIN
  ////////////////////////////////////////////////////////////
  public void windowActivated( WindowEvent e ) {}
  public void windowDeactivated( WindowEvent e ) {}
  public void windowClosed( WindowEvent e ) {}
  public void windowClosing( WindowEvent e ) {}
  public void windowDeiconified( WindowEvent e ) {}
  public void windowIconified( WindowEvent e ) {}
  public void windowOpened( WindowEvent e ) {}
  ////////////////////////////////////////////////////////////
  // WindowListener: END
  ////////////////////////////////////////////////////////////
  
  ///////////////////////////////////////////////////////////
  // interface XgmListener: END
  ///////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////
  // interface XgmTableListener: BEGIN
  ///////////////////////////////////////////////////////////
  public void dataChanged( XgmTableEvent e )
  {
    XgmTableModel xtm = e.getTableModel();
    try
    {
      if( xtm.getModelName() != null && xtm.getModelName().equals( DOC_LIN_TABLE ) )
      {
        if( e.getType() == XgmTableEvent.DELETE )
        {
          MpBizError error = mpBizDoc.deleteLines( e.getRows() );
          switch( error.getErrorType() )
          {
            case NO_ERROR:
              break;
            default:
              setFormFromMpBizDoc();
              JOptionPane.showMessageDialog( xgmDocFrame.getSwingContainer(), error.getMessage() );
              break;
          }
          mpBizDoc.setNeedsRecalc( true );
          validateDocument( false );
          updateTotals();
          updatePayTable();
          setFormFromMpBizDoc();
        }
      }
      else
      {
        mpBizDoc.setNeedsRecalc( true );
        updatePayTable();
        return;
      }
    }
    catch( Exception e1 )
    {
      logger.error( e1.getMessage(), e1 );
      JOptionPane.showMessageDialog( getDocFrame().getSwingContainer(), e1.getMessage() );
    }
    
    int col = e.getColumn();
    if ( col < 0 )
      return;
    
    if( xtm.getModelName().equals( DOC_LIN_TABLE ) &&
        col != idxColumnOrgTipoEntId && 
        col != idxColumnOrgTipoDocId && 
        col != idxColumnOrgDocId&& 
        col != idxColumnDescricao &&
        e.getType() != XgmTableEvent.DELETE )
    {
      mpBizDoc.setNeedsRecalc( true );
      int row = e.getRow( 0 );
      Double o = (Double) xtm.getValueAt( row, idxColumnTotalComTaxa ); 
      if ( o == null )
        return;
//      double valor = o.doubleValue();
//      try
//      {
//        xtm.setValueAt(
//          new Double( Tools.roundDouble( o, MpBizDoc.ROUND_LINE_TOTAL ) ), 
//          row, idxColumnTotalSemTaxas, false );
//      }
//      catch( Exception e1 )
//      {
//        String msg = e1.getLocalizedMessage();
//        DebugFactory.printWarning( msg );
//        e1.printStackTrace();
//        JOptionPane.showMessageDialog( getDocFrame().getSwingContainer(), msg );
//        return;
//      }
      if ( o > 0.0 )
      {
        XgmTextField btfTotalDoc = 
          (XgmTextField) docPanel.getComponentByName( DbDoc.FIELDS[ DbDoc.TOTAL_COM_TAXAS ] );
        try
        {
          setMpBizDocFromForm();
          validateDocument( false );
          Double total = mpBizDoc.getDoc().getTotalComTaxas();
          btfTotalDoc.setComponentValueFromObject( total );
          updateTotals();
          updatePayTable();
        }
        catch( Exception e1 )
        {
          String msg = e1.getLocalizedMessage();
          logger.error( e1.getMessage(), e1 );
          JOptionPane.showMessageDialog( getDocFrame().getSwingContainer(), msg );
                docPanel.getSwingContainer().repaint();
        }
      }
    }

  }
  
  ///////////////////////////////////////////////////////////
  // interface XgmTableEvent: END
  ///////////////////////////////////////////////////////////

}

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.