MpDocFactory.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 » MpDocFactory.java
/*
 * $Log: MpDocFactory.java,v $
 */

package com.m16e.mpbiz.docs;

import com.m16e.mpbiz.common.MpBizAppConfig;
import com.m16e.mpbiz.common.MpBizAppContext;
import com.m16e.mpbiz.common.bizclasses.MpBizCache;
import com.m16e.mpbiz.common.bizclasses.Taxa;
import com.m16e.mpbiz.common.MpBizAppConstants;
import com.m16e.mpbiz.ents.MpBizEnt;
import com.m16e.mpbiz.tables.DbAppLogger;
import com.m16e.mpbiz.tables.DbBillOfMaterials;
import com.m16e.mpbiz.tables.DbCostCenter;
import com.m16e.mpbiz.tables.DbDaMnft;
import com.m16e.mpbiz.tables.DbDaMnftTask;
import com.m16e.mpbiz.tables.DbDaMnftTaskItem;
import com.m16e.mpbiz.tables.DbDoc;
import com.m16e.mpbiz.tables.DbDocAddress;
import com.m16e.mpbiz.tables.DbDocAglutinator;
import com.m16e.mpbiz.tables.DbDocAglutinatorLines;
import com.m16e.mpbiz.tables.DbDocEstado;
import com.m16e.mpbiz.tables.DbDocEstimate;
import com.m16e.mpbiz.tables.DbDocLin;
import com.m16e.mpbiz.tables.DbDocLinPending;
import com.m16e.mpbiz.tables.DbDocPag;
import com.m16e.mpbiz.tables.DbDocTaxa;
import com.m16e.mpbiz.tables.DbDocTransport;
import com.m16e.mpbiz.tables.DbEnt;
import com.m16e.mpbiz.tables.DbEntFin;
import com.m16e.mpbiz.tables.DbProd;
import com.m16e.mpbiz.tables.DbProdArm;
import com.m16e.mpbiz.tables.DbProdInvent;
import com.m16e.mpbiz.tables.DbProdLot;
import com.m16e.mpbiz.tables.DbProdLotArm;
import com.m16e.mpbiz.tables.DbProdLotInvent;
import com.m16e.mpbiz.tables.DbTabArm;
import com.m16e.mpbiz.tables.DbTabDocProps;
import com.m16e.mpbiz.tables.DbTabMoeda;
import com.m16e.mpbiz.tables.DbTabTipoDoc;
import com.m16e.mpbiz.tables.DbTabTipoEnt;
import com.m16e.mpbiz.tables.DbTabTipoProd;
import com.m16e.mpbiz.tables.DbTabUniMov;
import com.m16e.mpbiz.tables.DbTotEnt;
import com.m16e.mpbiz.tables.DbTotProd;
import com.m16e.tools.MpAppContext;
import com.m16e.tools.MpDay;
import com.m16e.tools.Tuple;
import com.m16e.tools.datamodels.ComboData;
import com.m16e.tools.db.Database;
import com.m16e.tools.db.DatabaseException;
import com.m16e.tools.db.DatabaseProvider;
import com.m16e.tools.db.DbWorkingTable;
import com.m16e.tools.gui.MpSplashFrame;
import com.m16e.tools.gui.XgmDateChooser;
import com.m16e.tools.xgm.XgmException;
import com.m16e.tools.xml.XmlException;
import com.m16e.tools.xml.XmlTreeNode;
import com.m16e.tools.xml.XmlTreeNodeable;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
import org.apache.log4j.Logger;

///////////////////////////////////////////////////////////////
public class MpDocFactory 
{
  static Logger logger = Logger.getLogger( MpDocFactory.class );

  // some VERY UGLY constants...
  public final static int TENT_CUSTOMER = MpBizAppConstants.TENT_CUSTOMER;
  public final static int TENT_SUPPLIER = MpBizAppConstants.TENT_SUPPLIER;
//  public final static int PATIENT = 11;
//  public final static int DOCTOR = 12;
//  public final static int AGREEMENT = 13;

//  public final static int TMP_CONTACT_ID = -1;

  public final static int TENT_BANK = MpBizAppConstants.TENT_BANK;
  public final static int TENT_INTERNAL = MpBizAppConstants.TENT_INTERNAL;
  public final static int TENT_SELLER = MpBizAppConstants.TENT_SELLER;
  
  // ent
  public final static int DEFAULT_SYSTEM_ENT = MpBizAppConstants.DEFAULT_SYSTEM_ENT_ID;
  public final static int INTERNAL_ENT = MpBizAppConstants.INTERNAL_ENT_ID;
  
  // special prods
  public final static int DEFAULT_PROD = MpBizAppConstants.DEFAULT_PROD;

  // paracelso
  public static final int PRIVATE_AGREEMENT_ENT_ID = MpBizAppConstants.PRIVATE_AGREEMENT_ENT_ID;
  public static final int PRIVATE_AGREEMENT_ID = MpBizAppConstants.PRIVATE_AGREEMENT_ID;

  // document types
  public final static int TDOC_ORDER = MpBizAppConstants.TDOC_ORDER;
  public final static int TDOC_INVOICE = MpBizAppConstants.TDOC_INVOICE;
  public final static int V_DINHEIRO = MpBizAppConstants.V_DINHEIRO;
  public final static int TDOC_INVOICE_PRO_FORMA = MpBizAppConstants.TDOC_INVOICE_PRO_FORMA;
  public final static int TDOC_RETURN = MpBizAppConstants.TDOC_RETURN;
  
  public final static int RESERVATION = MpBizAppConstants.RESERVATION;
  public final static int TDOC_REQUEST = MpBizAppConstants.TDOC_REQUEST;
  
  public final static int TDOC_CREDIT_NOTE = MpBizAppConstants.TDOC_CREDIT_NOTE;
  public final static int TDOC_DEBIT_NOTE = MpBizAppConstants.TDOC_DEBIT_NOTE;
  public final static int TDOC_LANCAMENTO_CRED = MpBizAppConstants.TDOC_LANCAMENTO_CRED;
  public final static int TDOC_LANCAMENTO_DEB = MpBizAppConstants.TDOC_LANCAMENTO_DEB;
  public final static int TDOC_SHIPPING_NOTE = MpBizAppConstants.TDOC_SHIPPING_NOTE;
  public final static int TDOC_TRANSPORT_NOTE = MpBizAppConstants.TDOC_TRANSPORT_NOTE;
  public final static int TDOC_MANUFACTURE_ORDER = MpBizAppConstants.TDOC_MANUFACTURE_ORDER;
  
  public final static int TDOC_SAIDA_ARMAZEM = MpBizAppConstants.TDOC_SAIDA_ARMAZEM;
  public final static int TDOC_ENTRADA_ARMAZEM = MpBizAppConstants.TDOC_ENTRADA_ARMAZEM;
  public final static int TDOC_TRANSF_ARMAZEM = MpBizAppConstants.TDOC_TRANSF_ARMAZEM;
  public final static int TDOC_SAIDA_PRODUCAO = MpBizAppConstants.TDOC_SAIDA_PRODUCAO;
  public final static int TDOC_ENTRADA_PRODUCAO = MpBizAppConstants.TDOC_ENTRADA_PRODUCAO;
  public final static int TDOC_ACERTO_INVENTARIO = MpBizAppConstants.TDOC_ACERTO_INVENTARIO;
  
  public final static int TDOC_RECEIPT = MpBizAppConstants.TDOC_RECEIPT;
  
  public final static int TDOC_ESTIMATE = MpBizAppConstants.TDOC_ESTIMATE;

  public final static int PRIVATE_DOCS = MpBizAppConstants.PRIVATE_DOCS;
  public final static int PROD_DECOMP = MpBizAppConstants.PROD_DECOMP;
  public final static int TDOC_CONSULTATION_NOTE =  MpBizAppConstants.TDOC_CONSULTATION_NOTE;

  public final static int TDOC_START_OF_SHIFT = MpBizAppConstants.TDOC_START_OF_SHIFT;
  public final static int TDOC_END_OF_SHIFT = MpBizAppConstants.TDOC_END_OF_SHIFT;
  
  public final static int PAG_NUMERARIO = MpBizAppConstants.PAYMENT_CASH;
  public final static int PAG_CHEQUE = MpBizAppConstants.PAYMENT_CHECK;
  public final static int PAG_MB = MpBizAppConstants.PAG_MB;
  public final static int PAG_VISA = MpBizAppConstants.PAG_VISA;
  public final static int PAG_OUTROS = MpBizAppConstants.PAG_OUTROS;
  
  public final static int IVA_ISENTO = MpBizAppConstants.IVA_ISENTO;
  
  // doc_address types
  public final static int DOC_ADDRESS_TYPE_REQUESTER = MpBizAppConstants.DOC_ADDRESS_TYPE_REQUESTER;
  public final static int DOC_ADDRESS_TYPE_SHIPPING = MpBizAppConstants.DOC_ADDRESS_TYPE_SHIPPING;
  
  // tab_tax
  public final static int TAB_TAX_SRC_TAX_RETENTION = MpBizAppConstants.TAB_TAX_SRC_TAX_RETENTION;
  
  // tab_meio_pag
  public final static int TAB_MEIO_PAG_NUMERARIO = MpBizAppConstants.TAB_MEIO_PAG_NUMERARIO;
  public final static int TAB_MEIO_PAG_N_CREDITO = MpBizAppConstants.TAB_MEIO_PAG_N_CREDITO;
  
  // pending_state
  public final static int PEND_UNPROCESSED = MpBizAppConstants.PEND_UNPROCESSED;
  public final static int PEND_ORDERED = MpBizAppConstants.PEND_ORDERED;
  public final static int PEND_PARTIALLY_PROCESSED = MpBizAppConstants.PEND_PARTIALLY_PROCESSED;
  public final static int PEND_UNAVAILABLE = MpBizAppConstants.PEND_UNAVAILABLE;
  public final static int PEND_LEGACY = MpBizAppConstants.PEND_LEGACY;
  public final static int PEND_PROCESSED = MpBizAppConstants.PEND_PROCESSED;
  
  public final static String ICON_FACTURAR = MpBizAppConstants.ICON_FACTURAR;
  // end of ugliness...
  
  public final static int PROD_LINE = MpBizAppConstants.PROD_LINE;
  public final static int DOC_LINE = MpBizAppConstants.DOC_LINE;
  public final static int NO_LINE = MpBizAppConstants.NO_LINE;
  public final static int FIXED_PROD_LINE = MpBizAppConstants.FIXED_PROD_LINE;

  MpBizAppContext mpBizAppContext = null;
  DatabaseProvider dbProvider = null;
  
  MpDay defaultDocDate = new MpDay();

//  DbCacheFactory systemChachedTables = null;
  MpBizCache bizCache = MpBizCache.getInstance();

  private static MpDocFactory onlyInstance = new MpDocFactory();
  
  ///////////////////////////////////////////////////////////////
  private MpDocFactory() 
  {
    logger.info( "MpDocFactory:\n>>>>>\nData doc: " + defaultDocDate );

    mpBizAppContext = MpBizAppContext.getInstance();
    MpAppContext mac = MpAppContext.getInstance();
    dbProvider = mac.getDatabaseProvider();
  }
  
  ////////////////////////////////////////////////////////////
  public static MpDocFactory getInstance() { return onlyInstance; }
  
  ////////////////////////////////////////////////////////////
  public void setTaxas( Taxa[] taxas )
  {
    bizCache.setTaxas( taxas );
  }

  ////////////////////////////////////////////////////////////
  public Taxa[] getTaxas()
  {
    return bizCache.getTaxas();
  }
  
  ////////////////////////////////////////////////////////////
  public List<Taxa> getTaxas( MpDay[] interval )
  {
    return bizCache.getTaxas( interval );
  }
  
  ////////////////////////////////////////////////////////////
  public Taxa getTaxa( Integer taxaId, Integer taxZoneId, MpDay when )
  {
    return bizCache.getTaxa( taxaId, taxZoneId, when );
  }

  ////////////////////////////////////////////////////////////
  public Taxa getTaxByValue( Double value )
  {
    return bizCache.getTaxByValue( value );
  }

  ////////////////////////////////////////////////////////////
  public void importEnts( BufferedReader br ) 
  {
    Connection con = null;
    boolean success = false;
    boolean inRow = false;
    try
    {
      con = dbProvider.getDatabase().getConnection();
      con.setAutoCommit( false );
      StringBuffer sb = new StringBuffer();
      String aux;
      int count = 0;
      while( (aux = br.readLine()) != null )
      {
        if( aux.trim().startsWith( "<" + DbWorkingTable.TAG_ROW ) )
        {
          sb = new StringBuffer( aux + "\n" );
          inRow = true;
        }
        else if( aux.trim().startsWith( "</" + DbWorkingTable.TAG_ROW + ">" ) )
        {
          sb.append( aux + "\n" );
          XmlTreeNode xtnEnt = new XmlTreeNode();
          xtnEnt.fromXml( sb.toString().trim() );
          MpBizEnt mpBizEnt = new MpBizEnt();
          mpBizEnt.fromXmlTreeNode( xtnEnt );
          try
          {
            int entId = mpBizEnt.getEntId();
            if( entId != 0 && entId != INTERNAL_ENT )
            {
              if( DbEnt.getById( entId ) != null )
              {
                mpBizEnt.setChangedFields( true );
                mpBizEnt.update();
              }
              else
              {
                mpBizEnt.insert();
              }
            }
          }
          catch( Exception e ) 
          {
            con.rollback();
            System.out.println( 
              "FAILED: Importing Ent: " + mpBizEnt.getEntId() +
              "\n" + e.getMessage() );
            e.printStackTrace();
          }
          con.commit();
          count++;
          sb.setLength( 0 );
          System.out.println( "Importing Ent: " + mpBizEnt.getEntId() );
        }
        else if( inRow )
          sb.append( aux + "\n" );
      }
      success = true;
      System.out.println( "Ents inserted: " + count ); 
    }
    catch( Exception e )
    {
      logger.error( e.getMessage(), e );
    }
    finally
    {
      try {
        if( !success ) con.rollback();
        else con.commit();
        con.setAutoCommit( true );
      } catch( SQLException e ) { logger.error( e.getMessage(), e ); }
    }
  }
  
  ////////////////////////////////////////////////////////////
  public void exportDocs( PrintWriter pw, String where, String order ) 
  throws SQLException, MpDocException, XgmException, XmlException, DatabaseException
  {
    DbDoc dbDoc = new DbDoc();
    java.util.List<Tuple> docs = dbDoc.select( where, order );
    for( int f = 0; f < docs.size(); f++ )
    {
      Integer tipoEntId = DbDoc.getTipoEntId( docs.get( f ) );
      Integer tipoDocId = DbDoc.getTipoDocId( docs.get( f ) );
      Integer docId = DbDoc.getDocId( docs.get( f ) );
      System.out.println(
        "Exporting: " + tipoEntId + "; " + tipoDocId + ", " + docId + "..." );
      MpBizDoc mpBizDoc = MpBizDoc.getById( tipoEntId, tipoDocId, docId );
      if( mpBizDoc == null )
        throw new MpDocException(
          "Documento inexistente:\n  tipoEntId: " + tipoEntId +
          "\n  tipoDocId: " + tipoDocId +
          "\n  docId: " + docId );
      //mpBizDoc.computeTotal();
      mpBizDoc.cleanAuxValues();
      mpBizDoc.clearTaxes();
      pw.println( mpBizDoc.toXmlTreeNode().toXml( 1 ) );
      
    }
  }
  
  ////////////////////////////////////////////////////////////
  public void exportDocs( PrintWriter pw, Integer tipoEntId, Integer tipoDocId, Integer docId ) 
  throws SQLException, MpDocException, XgmException, XmlException, DatabaseException
  {
    StringBuffer sb = new StringBuffer();
    if( tipoEntId != null )
      sb.append( DbDoc.FN_TIPO_ENT_ID + " = " + tipoEntId );
    if( tipoDocId != null )
    {
      if( sb.length() > 0 )
        sb.append( " and " );
      sb.append( DbDoc.FN_TIPO_DOC_ID + " = " + tipoDocId );
    }
    if( docId != null )
    {
      if( sb.length() > 0 )
        sb.append( " and " );
      sb.append( DbDoc.FN_DOC_ID + " = " + docId );
    }
    
    DbDoc dbDoc = new DbDoc();
    java.util.List<Tuple> docs = dbDoc.select( sb.toString(), null );
    for( int f = 0; f < docs.size(); f++ )
    {
      Integer dTipoEntId = DbDoc.getTipoEntId( docs.get( f ) );
      Integer dTipoDocId = DbDoc.getTipoDocId( docs.get( f ) );
      Integer dDocId = DbDoc.getDocId( docs.get( f ) );
      System.out.println(
        "Exporting: " + dTipoEntId + "; " + dTipoDocId + ", " + dDocId + "..." );
      MpBizDoc mpBizDoc = MpBizDoc.getById( tipoEntId, tipoDocId, docId );
      if( mpBizDoc == null )
        throw new MpDocException(
          "Documento inexistente:\n  tipoEntId: " + dTipoEntId +
          "\n  tipoDocId: " + dTipoDocId +
          "\n  docId: " + dDocId );
      //mpBizDoc.computeTotal();
      mpBizDoc.cleanAuxValues();
      mpBizDoc.clearTaxes();
      XmlTreeNodeable xtnDoc = mpBizDoc.toXmlTreeNode();

      List<DbBillOfMaterials> bomList =
        DbBillOfMaterials.getList(
          DbBillOfMaterials.FN_TIPO_ENT_ID + " = ? and " +
          DbBillOfMaterials.FN_TIPO_DOC_ID + " = ? and " +
          DbBillOfMaterials.FN_DOC_ID + " = ?",
          DbBillOfMaterials.FN_SRC_PROD_ID,
          dbDoc.getTipoEntId(),
          dbDoc.getTipoDocId(),
          dbDoc.getDocId() );
      if( bomList.size() > 0 )
      {
        for( DbBillOfMaterials bom : bomList )
        {
          XmlTreeNode xtnBom = new XmlTreeNode( xtnDoc, DbBillOfMaterials.T_NAME );
          xtnBom.insert( bom.toXmlTreeNode() );
        }
      }
      DbDocAglutinator aglut =
        DbDocAglutinator.getSingleRecord(
          DbDocAglutinator.FN_MAIN_TIPO_ENT_ID + " = ? and " +
          DbDocAglutinator.FN_MAIN_TIPO_DOC_ID + " = ? and " +
          DbDocAglutinator.FN_MAIN_DOC_ID + " = ?",
          dbDoc.getTipoEntId(),
          dbDoc.getTipoDocId(),
          dbDoc.getDocId() );
      if( aglut != null )
      {
        XmlTreeNode xtnAglut = new XmlTreeNode( xtnDoc, DbDocAglutinator.T_NAME );
        xtnAglut.insert( aglut.toXmlTreeNode() );

        List<DbDocAglutinatorLines> aglutList =
          DbDocAglutinatorLines.getList(
            DbDocAglutinatorLines.FN_DOC_AGLUTINATOR_ID + " = ?",
            null,
            aglut.getDocAglutinatorId() );
        for( DbDocAglutinatorLines dal : aglutList )
        {
          XmlTreeNode xtnAglutLines = new XmlTreeNode( xtnDoc, DbDocAglutinatorLines.T_NAME );
          xtnAglutLines.insert( dal.toXmlTreeNode() );
        }
        DbDaMnft mnft =
          DbDaMnft.getSingleRecord(
            DbDaMnft.FN_DOC_AGLUTINATOR_ID + " = ?",
            aglut.getDocAglutinatorId() );
        if( mnft != null )
        {
          XmlTreeNode xtnMnft = new XmlTreeNode( xtnDoc, DbDaMnft.T_NAME );
          xtnMnft.insert( mnft.toXmlTreeNode() );
          List<DbDaMnftTask> mnftTaskList =
            DbDaMnftTask.getList(
              DbDaMnftTask.FN_DOC_AGLUTINATOR_ID + " = ?",
              DbDaMnftTask.FN_TASK_ID,
              aglut.getDocAglutinatorId() );
          for( DbDaMnftTask mnftTask : mnftTaskList )
          {
            XmlTreeNode xtnAglutLines = new XmlTreeNode( xtnDoc, DbDaMnftTask.T_NAME );
            xtnAglutLines.insert( mnftTask.toXmlTreeNode() );
          }
          List<DbDaMnftTaskItem> mnftTaskItemList =
            DbDaMnftTaskItem.getList(
              DbDaMnftTaskItem.FN_DOC_AGLUTINATOR_ID + " = ?",
              DbDaMnftTaskItem.FN_TASK_ID + ", " + DbDaMnftTaskItem.FN_TASK_ITEM_ID,
              aglut.getDocAglutinatorId() );
          for( DbDaMnftTaskItem mnftTaskItem : mnftTaskItemList )
          {
            XmlTreeNode xtnAglutLines = new XmlTreeNode( xtnDoc, DbDaMnftTaskItem.T_NAME );
            xtnAglutLines.insert( mnftTaskItem.toXmlTreeNode() );
          }
        }
      }
      pw.println( xtnDoc.toXml( 1 ) );
    }
  }
  
  ////////////////////////////////////////////////////////////
  public void importDocs( BufferedReader br )
  {
    Database database = null;
    boolean success = false;
    StringBuffer sb = new StringBuffer();
    String aux;
    int count = 0;
    try
    {
      database = MpAppContext.getInstance().getDatabase();
      while( (aux = br.readLine()) != null )
      {
        sb.append( aux + "\n" );
        if( aux.trim().startsWith( "</" + MpBizDoc.TAG_MP_BIZ_DOC + ">" ) )
        {
          database.beginTransaction();
          XmlTreeNode xtn = new XmlTreeNode();
          xtn.fromXml( sb.toString().trim() );
          MpBizDoc mpBizDoc = new MpBizDoc();
          mpBizDoc.fromXmlTreeNode( xtn );
          System.out.println(
            "Importing Doc: " + mpBizDoc.getTipoEntId() + "; " +
            mpBizDoc.getTipoDocId() + "; " + mpBizDoc.getDocId() +
            ": " + mpBizDoc.getDataDoc() );
          mpBizDoc.getDoc().setAuxDouble1( 0.0 );
          for( MpBizDocLin mdl : mpBizDoc.getDocLines() )
          {
            DbDocLin dl = mdl.getDocLin();
            dl.setAuxDouble1( 0.0 );
            dl.setAuxItemId( 0 );
            Integer orgLinId = dl.getOrgTipoDocId();
            if( orgLinId == null || orgLinId == 0 )
            {
              dl.setOrgTipoEntId( null );
              dl.setOrgTipoDocId( null );
              dl.setOrgDocId( null );
              dl.setOrgDocLinId( null );
            }
          }
          mpBizDoc.setValidatePrice( false );
          mpBizDoc.setNeedsRecalc( true );
          mpBizDoc.setNewDoc( false );
          mpBizDoc.setImporting( true );
          DbEntFin entFin = new DbEntFin();
          entFin.setEntId( mpBizDoc.getEntId() );
          entFin.setTipoEntId( mpBizDoc.getTipoEntId() );
          if( !entFin.getById() )
          {
            entFin.insert();
          }
          mpBizDoc.createDocument();
          // doc_aglutinator_lines
          java.util.List<XmlTreeNodeable> xtnBomList =
            xtn.getChildrenByTagName( DbBillOfMaterials.T_NAME );
          for( XmlTreeNodeable x : xtnBomList )
          {
            DbBillOfMaterials bom = new DbBillOfMaterials();
            bom.updateFromTreeNode( x );
          }

          // doc_aglutinator
          XmlTreeNodeable xtnDocAglut =
            xtn.getChildByTagName( false, DbDocAglutinator.T_NAME );
          if( xtnDocAglut != null )
          {
            DbDocAglutinator docAglutinator = new DbDocAglutinator();
            docAglutinator.updateFromTreeNode( xtnDocAglut );

            // doc_aglutinator_lines
            java.util.List<XmlTreeNodeable> xtnDalList =
              xtn.getChildrenByTagName( DbDocAglutinatorLines.T_NAME );
            for( XmlTreeNodeable x : xtnDalList )
            {
              DbDocAglutinatorLines daLine = new DbDocAglutinatorLines();
              daLine.updateFromTreeNode( x );
            }

            // da_mnft
            XmlTreeNodeable xtnDaMnft =
              xtn.getChildByTagName( false, DbDaMnft.T_NAME );
            if( xtnDaMnft != null )
            {
              DbDaMnft mnft = new DbDaMnft();
              mnft.updateFromTreeNode( xtnDaMnft );

              // da_mnft_task
              java.util.List<XmlTreeNodeable> xtnMnftTasks =
                xtn.getChildrenByTagName( DbDaMnftTask.T_NAME );
              for( XmlTreeNodeable x : xtnMnftTasks )
              {
                DbDaMnftTask mnftTask = new DbDaMnftTask();
                mnftTask.updateFromTreeNode( x );
              }
              // da_mnft_task_item
              java.util.List<XmlTreeNodeable> xtnMnftTaskItems =
                xtn.getChildrenByTagName( DbDaMnftTaskItem.T_NAME );
              for( XmlTreeNodeable x : xtnMnftTaskItems )
              {
                DbDaMnftTaskItem mnftTaskItem = new DbDaMnftTaskItem();
                mnftTaskItem.updateFromTreeNode( x );
              }
            }
          }

          count++;
          sb.setLength( 0 );
          database.commitTransaction();
          success = true;
        }
      }
    }
    catch( Exception e )
    {
      logger.error( e.getMessage(), e );
    }
    finally
    {
      if( !success )
      {
        try
        { database.rollbackTransaction(); }
        catch( SQLException se )
        {}
      }
    }
    System.out.println( "Docs inserted: " + count );
  }

  ////////////////////////////////////////////////////////////
  public void exportEnts( PrintWriter pw, String where, String order ) 
  throws SQLException, MpDocException, XgmException, XmlException, DatabaseException
  {
    DbEnt dbEnt = new DbEnt();
    java.util.List<Tuple> ents = dbEnt.select( where, order );
    for( int f = 0; f < ents.size(); f++ )
    {
      MpBizEnt mpBizEnt = new MpBizEnt();
      Integer entId = DbEnt.getEntId( ents.get( f ) );
      System.out.println( "Exporting: " + entId + "..." );
      mpBizEnt.setEntId( entId );
      if( !mpBizEnt.getById() )
        throw new MpDocException(
          "Entidade inexistente:\n  entId: " + entId );
      pw.println( mpBizEnt.toXmlTreeNode().toXml( 0 ) );
    }
  }
  
  ////////////////////////////////////////////////////////////
  public MpDay getDefaultDocDate() 
  { 
    return defaultDocDate; 
  }
  
  ////////////////////////////////////////////////////////////
  public void setDefaultDocDate( MpDay date ) 
  { 
    defaultDocDate = date;
    logger.info(
      "set defaultDocDate to: " + defaultDocDate );
  }
  
  ////////////////////////////////////////////////////////////
  public void changeDefaultDocDate()
  throws XgmException 
  { 
    XgmDateChooser xdc = new XgmDateChooser();
    xdc.init( true, false );
    xdc.setDate( defaultDocDate.getDate(), null );
    
    MpDay[] newDate = xdc.getDate();
    if( newDate == null )
      return;
    
    setDefaultDocDate( newDate[0] );
  }
  
  ////////////////////////////////////////////////////////////
  public int getDocFactor( int tipoDocId )
    throws MpDocException, SQLException
  {
    CallableStatement cs =
      dbProvider.getDatabase().getCallableStatement(
        "call mpbiz_get_mov_doc_factor( ?, ? )" );
    cs.setInt( 1, TENT_CUSTOMER  );
    cs.setInt( 2, tipoDocId );
    ResultSet rs = cs.executeQuery();
    int val = 0;
    if( rs.next() )
    {
      val = rs.getInt( 1 );
    }
    rs.close();
    cs.close();
    return val;
  }
  
  
  ////////////////////////////////////////////////////////////
  public static boolean prodAfStocks( int prodId )
    throws MpDocException, SQLException
  {
    CallableStatement cs =
      MpAppContext.getInstance().getDatabase().getCallableStatement(
        "call mpbiz_get_tipo_prod_af_stocks( " + prodId + " )" );
    ResultSet rs = cs.executeQuery();
    boolean val = false;
    if( rs.next() )
    {
      val = rs.getBoolean( 1 );
    }
    else
      throw new MpDocException( "Produto desconhecido ( " + prodId + " )" );
    rs.close();
    cs.close();
    return val;
  }
  
  ////////////////////////////////////////////////////////////
  public static MpDay getDataDoc( int tipoEntId, int tipoDocId, int docId )
  throws MpDocException, SQLException
  {
    CallableStatement cs =
      MpAppContext.getInstance().getDatabase().getCallableStatement(
        "call mpbiz_get_data_doc( " + tipoEntId + ", " + tipoDocId + ", " + docId + " )" );
    ResultSet rs = cs.executeQuery();
    MpDay val = null;
    if( rs.next() )
    {
      val = new MpDay( rs.getDate( 1 ) );
    }
    else
      throw new MpDocException( "Documento desconhecido ( " + tipoEntId + ", " + tipoDocId + ", " + docId + " )" );
    rs.close();
    cs.close();
    return val;
  }
  
  ////////////////////////////////////////////////////////////
  public MpDay getDataLimitePagamento( 
    Integer tipoEntId, Integer entId, MpDay date )
    throws SQLException
  {
    Database database = dbProvider.getDatabase();
    String query =
      "select date '" + date + 
      "' + ( select " + 
      DbEntFin.FIELDS[ DbEntFin.PRAZO_PAG ] +
      " from " + DbEntFin.T_NAME + " where " +
      DbEntFin.FIELDS[ DbEntFin.TIPO_ENT_ID ] + " = " +
      tipoEntId + " and " +
      DbEntFin.FIELDS[ DbEntFin.ENT_ID ] + " = " + entId + " )";
    Statement stmt = database.getConnection().createStatement();
    if( logger.isDebugEnabled() )
    {
      logger.debug( "query: " + query );
    }
    ResultSet rs = stmt.executeQuery( query );
    MpDay newDate = new MpDay();
    if( rs.next() )
      newDate = new MpDay( rs.getDate( 1 ) );
    rs.close();
    stmt.close();
    return newDate;
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanEntMovements()
    throws SQLException
  {
    Database database = dbProvider.getDatabase();
    Statement stmt = database.getConnection().createStatement();
    
    String update =
      "delete from " + DbTotEnt.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanEntMovements>\n  update: " + update );
    stmt.executeUpdate( update );
    
    update =
      "update " + DbEntFin.T_NAME + 
      " set " +
      DbEntFin.FIELDS[ DbEntFin.VOL_NEG ] + " = 0, " +
      DbEntFin.FIELDS[ DbEntFin.CREDITO ] + " = 0, " +
      DbEntFin.FIELDS[ DbEntFin.DEBITO ] + " = 0, " +
      DbEntFin.FIELDS[ DbEntFin.VAL_ENC ] + " = 0";
    System.out.println(
      "<MpDocfactory.cleanEntMovements>\n  update: " + update );
    stmt.executeUpdate( update );
    
    stmt.close();
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanProdMovements( boolean clearCosts )
    throws SQLException
  {
    Database database = dbProvider.getDatabase();
    Statement stmt = database.getConnection().createStatement();
    String update =
      "delete from " + DbProdInvent.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt.executeUpdate( update );
    stmt.close();
    
    stmt = database.getConnection().createStatement();
    update =
      "delete from " + DbProdLotInvent.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt.executeUpdate( update );
    stmt.close();
    
    stmt = database.getConnection().createStatement();
    update =
      "delete from " + DbTotProd.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt.executeUpdate( update );
    stmt.close();
    
    stmt = database.getConnection().createStatement();
    update =
      "delete from " + DbProdArm.T_NAME + 
      " where " + DbTabArm.FN_ARM_ID + " != 0";
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    stmt = database.getConnection().createStatement();
    if( clearCosts )
    {
    update = 
      "update " + DbProd.T_NAME + 
      " set " + DbProd.FIELDS[ DbProd.QUANT ] + " = 0," +
      DbProd.FIELDS[ DbProd.P_MED_CUSTO ] + " = 0," +
      DbProd.FIELDS[ DbProd.DATA_ULT_P_CUSTO ] + " = null";
      
    }
    else
    {
      update =
        "update " + DbProd.T_NAME +
        " set " + DbProd.FIELDS[ DbProd.QUANT ] + " = 0";
    }
    System.out.println(
      "<MpDocFactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanMov( boolean clearCosts )
  throws MpDocException, SQLException
  {
    disableTriggers();
    cleanMovTables();
    cleanEntMovements();
    cleanProdMovements( clearCosts );
    enableTriggers();
  }

  ////////////////////////////////////////////////////////////
  static final String ENABLE_TRIGGERS = "mpbiz_enable_triggers()";
  static final String DISABLE_TRIGGERS = "mpbiz_disable_triggers()";

  private void disableTriggers() 
  throws SQLException
  {
    Database database = dbProvider.getDatabase();
    CallableStatement cs = database.getCallableStatement( "call " + DISABLE_TRIGGERS );
    cs.executeUpdate();
    cs.close();
  }

  private void enableTriggers() 
  throws SQLException
  {
    Database database = dbProvider.getDatabase();
    CallableStatement cs = database.getCallableStatement( "call " + ENABLE_TRIGGERS );
    cs.executeUpdate();
    cs.close();
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanDocMovements()
    throws SQLException
  {
    Database database = dbProvider.getDatabase();
    Statement stmt = database.getConnection().createStatement();
    
    disableTriggers();
    
    // clean doc_lin
    String update =
      "delete from " + DbDocLin.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbTotProd.T_NAME +
      " where " + DbTotProd.FIELDS[ DbTotProd.PROD_ID ] + "!= 0";
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbProdArm.T_NAME +
      " where " + DbProdArm.FIELDS[ DbProdArm.PROD_ID ] + "!= 0";
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    
    // clean doc_taxa
    update =
      "delete from " + DbDocTaxa.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    // clean doc_estado
    update =
      "delete from " + DbDocEstado.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    // clean doc_pag
    update =
      "delete from " + DbDocPag.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    // clean doc_address
    update =
      "delete from " + DbDocAddress.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    // clean doc
    update =
      "delete from " + DbDoc.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    enableTriggers();
    
  }
  
  ////////////////////////////////////////////////////////////
  public void deleteAllDocs()
    throws SQLException
  {
    Database database = dbProvider.getDatabase();
    Statement stmt = database.getConnection().createStatement();
    String update =
      "delete from " + DbDocEstado.T_NAME;
    System.out.println(
      "<MpDocfactory.deleteAllDocs>\n  update: " + update );
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbDocLin.T_NAME;
    System.out.println(
      "<MpDocfactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbDocTransport.T_NAME;
    System.out.println(
      "<MpDocfactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbDocPag.T_NAME;
    System.out.println(
      "<MpDocfactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbDocTaxa.T_NAME;
    System.out.println(
      "<MpDocFactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbDocEstado.T_NAME;
    System.out.println(
      "<MpDocFactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    
    update =
      "delete from " + DbDoc.T_NAME;
    System.out.println(
      "<MpDocFactory.deleteAllDocs>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
  }
  
  ////////////////////////////////////////////////////////////
  public void rebuildMovAuxTables()
  throws MpDocException, XgmException, SQLException
  {
    Database database = dbProvider.getDatabase();
//    DbFactory dbProvider = (DbFactory) mpBizAppContext.getDatabaseProvider();
    Connection con = database.getConnection();
    boolean success = false;
    try
    {
      con.setAutoCommit( false );
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>" +
        "\n  removing entity data..." );
      cleanEntMovements();
      System.out.println( "  DONE" );
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>" +
        "\n  removing product data..." );
      cleanProdMovements( true );
      cleanDocMovements();
      //con.commit();
      System.out.println( "  DONE\n  STARTING REBUILD...\n" );
      DbDoc doc = new DbDoc();
      //DbDocLin dbDocLin = (DbDocLin) dbProvider.getTableByName( DbDocLin.T_NAME );
      int f = 0;
      String where =
        DbDoc.FIELDS[ DbDoc.DOC_ID ] + " > 0";
      java.util.List<DbDoc> docs =
        DbDoc.getList( where, DbDoc.FIELDS[ DbDoc.TS ] );
      for( f = docs.size() - 1; f >= 0 ; f-- )
      {
        Integer tipoEntId = docs.get( f ).getTipoEntId();
        Integer tipoDocId = docs.get( f ).getTipoDocId();
        Integer docId = docs.get( f ).getDocId();
        MpBizDoc mpBizDoc = MpBizDoc.getById( tipoEntId, tipoDocId, docId );
        if( mpBizDoc == null )
          throw new MpDocException(
            "Documento inexistente:\n  tipoEntId: " + tipoEntId +
            "\n  tipoDocId: " + tipoDocId +
            "\n  docId: " + docId );
        mpBizDoc.setValidatePrice( false );
        mpBizDoc.computeTotal();
        doc = mpBizDoc.getDoc();
        
        // debug
        tipoEntId = doc.getTipoEntId();
        tipoDocId = doc.getTipoDocId();
        docId = doc.getDocId();
        System.out.println(
          "<MpDocFactory.rebuildMovAuxTables.2>" +
          "\n  parsing doc:" +
          "\n    tipoEntId: " + tipoEntId +
          "\n    tipoDocId: " + tipoDocId +
          "\n    docId: " + docId +
          "\n    entId: " + doc.getEntId() );

        java.util.List<MpBizDocLin> docLins = mpBizDoc.getDocLines();
        int g = 0;
        for( MpBizDocLin mdl : docLins )
        {
          DbDocLin bean = mdl.getDocLin();
          if( tipoDocId.intValue() == TDOC_RECEIPT )
          {
            Statement stmt = database.getConnection().createStatement();
            String query =
              "select " + 
              DbDoc.FIELDS[ DbDoc.TOTAL_COM_TAXAS ] +
              " from " + DbDoc.T_NAME +
              " where " +
              DbDoc.FIELDS[ DbDoc.TIPO_ENT_ID ] + " = " +
              bean.getOrgTipoEntId() + " and " +
              DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] + " = " +
              bean.getOrgTipoDocId() + " and " +
              DbDoc.FIELDS[ DbDoc.DOC_ID ] + " = " +
              bean.getOrgDocId();
            ResultSet rs = stmt.executeQuery( query );
            if( rs.next() )
            {
              double tot = rs.getDouble( 1 );
              bean.setAuxDouble1( new Double( tot ) );
            }
            rs.close();
            stmt.close();
          }
        }
        mpBizDoc.deleteDoc( false );
//        mpBizDoc.setNewDoc( false );
//        mpBizDoc.persistDocument();
      }
      //con.commit();
      success = true;
    }
    catch( Exception e )
    {
      String msg = e.getMessage();
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>\n  EXCEPTION: " + msg );
      e.printStackTrace();
      throw new MpDocException( "DOC EXCEPTION:\n" + msg );
    }
    finally
    {
      try {
        if( success ) con.commit();
        else con.rollback();
        con.setAutoCommit( true );
      } catch( SQLException sqle2 ) { sqle2.printStackTrace(); }
    }
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanMovTables()
  throws MpDocException, SQLException
  {
    Database database = dbProvider.getDatabase();
    if( !database.inTransaction() )
    {
      throw new SQLException( "TRANSACTION HASDN'T STARTED!" );
    }
    
    System.out.println(
      "<MpDocFactory.cleanMovTables>" +
      "\n  removing data..." );

    Statement stmt = database.getConnection().createStatement();
    String update =
      "delete from " + DbTotProd.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt.executeUpdate( update );
    stmt.close();

    // clean doc_lin_pending
    update =
      "delete from " + DbDocLinPending.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    // mnft
    update = "delete from " + DbDaMnftTaskItem.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbDaMnftTask.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbDaMnft.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbDocAglutinatorLines.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbBillOfMaterials.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbDocAglutinator.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    // clean doc_lin
    String disableTrigger = "trg_delete_doc_lin_tuple";
    update = 
      "alter table " + DbDocLin.T_NAME + " disable trigger " + disableTrigger;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = "delete from " + DbDocLin.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update = 
      "alter table " + DbDocLin.T_NAME + " enable trigger " + disableTrigger;
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();
    
    update =
      "delete from " + DbProdLotInvent.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbProdInvent.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

//    update =
//      "delete from " + DbArmEnt.T_NAME;
//    System.out.println(
//      "<MpDocfactory.cleanMovTables>\n  update: " + update );
//    stmt = database.getConnection().createStatement();
//    stmt.executeUpdate( update );
//    stmt.close();
//
    update =
      "delete from " + DbTotProd.T_NAME +
      " where " + DbTotProd.FIELDS[ DbTotProd.PROD_ID ] + "!= 0";
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbProdLotArm.T_NAME + " where prod_id > 0";
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbProdLot.T_NAME + " where prod_id > 0";
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbProdArm.T_NAME + " where prod_id > 0 or arm_id > 0";
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

//    update =
//      "delete from " + DbTabArm.T_NAME + " where " +
//      DbTabArm.FN_ARM_ID + " != 0";
//    System.out.println(
//      "<MpDocfactory.cleanMovTables>\n  update: " + update );
//    stmt = database.getConnection().createStatement();
//    stmt.executeUpdate( update );
//    stmt.close();
//
    update = 
      "update " + DbProd.T_NAME + 
      " set " + DbProd.FIELDS[ DbProd.QUANT ] + " = 0," +
      DbProd.FIELDS[ DbProd.P_MED_CUSTO ] + " = 0," +
      DbProd.FIELDS[ DbProd.DATA_ULT_P_CUSTO ] + " = null";
    System.out.println(
      "<MpDocFactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbTotEnt.T_NAME;
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "update " + DbEntFin.T_NAME + 
      " set " +
      DbEntFin.FIELDS[ DbEntFin.VOL_NEG ] + " = 0, " +
      DbEntFin.FIELDS[ DbEntFin.CREDITO ] + " = 0, " +
      DbEntFin.FIELDS[ DbEntFin.DEBITO ] + " = 0";
    System.out.println(
      "<MpDocfactory.cleanMovTables>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    update =
      "delete from " + DbProdArm.T_NAME +
      " where " + DbProdArm.FIELDS[ DbProdArm.PROD_ID ] + "!= 0";
    System.out.println(
      "<MpDocfactory.cleanProdMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();


    // clean doc_taxa
    update =
      "delete from " + DbDocTaxa.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    // clean doc_transport
    update =
      "delete from " + DbDocTransport.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    // clean doc_estimate
    update =
      "delete from " + DbDocEstimate.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    // clean app_logger
    update =
      "delete from " + DbAppLogger.T_NAME;
    System.out.println(
      "<MpDocFactory.cleanDocMovements>\n  update: " + update );
    stmt = database.getConnection().createStatement();
    stmt.executeUpdate( update );
    stmt.close();

    System.out.println( "  DONE" );
    System.out.println(
      "<MpDocFactory.cleanMovTables>" +
      "\n  removing product data..." );
    cleanDocMovements();
  }
  
  ////////////////////////////////////////////////////////////
  public void cleanMovAuxTables()
    throws MpDocException, SQLException //, ParseException
  {
    Database database = dbProvider.getDatabase();
//    DbFactory dbProvider = (DbFactory) mpBizAppContext.getDatabaseProvider();
    Connection con = database.getConnection();
    boolean success = false;
    try
    {
      con.setAutoCommit( false );
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>" +
        "\n  removing entity data..." );
      cleanProdMovements( true );
      cleanEntMovements();
      System.out.println( "  DONE" );
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>" +
        "\n  removing product data..." );
      cleanDocMovements();
      //con.commit();
      success = true;
    }
    catch( SQLException e )
    {
      String msg = e.getMessage();
      System.out.println(
        "<MpDocFactory.rebuildMovAuxTables>\n  EXCEPTION: " + msg );
      e.printStackTrace();
      throw new MpDocException( "DOC EXCEPTION:\n" + msg );
    }
    finally
    {
      try {
        if( success ) con.commit();
        else con.rollback();
        con.setAutoCommit( true );
      } catch( SQLException sqle2 ) { sqle2.printStackTrace(); }
    }
  }
  
  ///////////////////////////////////////////////////////////////
  public DbTabMoeda getDbTabMoeda( int moedaId )
  {
    return bizCache.getDbTabMoeda( moedaId );
  }
  
  ///////////////////////////////////////////////////////////////
  public String getNomeMoeda( int moedaId )
  {
    return bizCache.getCurrencyName( moedaId );
  }
  
  ///////////////////////////////////////////////////////////////
  public Double getCotacaoMoeda( Integer moedaId )
  {
    return bizCache.getCotacaoMoeda( moedaId );
  }
  
  ///////////////////////////////////////////////////////////////
  public void refreshTables( MpSplashFrame splashFrame )
  {
    bizCache.refreshTables( splashFrame );
  }
  
  ///////////////////////////////////////////////////////////
  public int getDocPropsStartNumber( Integer tipoEntId, Integer tipoDocId )
  {
    return bizCache.getDocPropsStartNumber( tipoEntId, tipoDocId );
  }
  
  ///////////////////////////////////////////////////////////
  public double getValorTaxa( Integer taxaId, Integer taxZoneId, MpDay when )
  {
    return bizCache.getValorTaxa( taxaId, taxZoneId, when );
  }
  
  ///////////////////////////////////////////////////////////
  public String getDescricaoTaxa( Integer taxaId, Integer taxZoneId, MpDay when )
  {
    return bizCache.getDescricaoTaxa( taxaId, taxZoneId, when );
  }
  
  ////////////////////////////////////////////////////////////
  public int getDocNumCopias( Integer tipoEntId, Integer tipoDocId )
  {
    return bizCache.getDocNumCopias( tipoEntId, tipoDocId );
  }
  
  ////////////////////////////////////////////////////////////
  public String getDocName( Integer tipoEntId, Integer tipoDocId )
  {
    return bizCache.getDocName( tipoEntId, tipoDocId );
  }
  
  ////////////////////////////////////////////////////////////
  public DbTabDocProps getDocProps( Integer tipoEntId, Integer tipoDocId )
  {
    return bizCache.getDocProps( tipoEntId, tipoDocId );
  }

  ////////////////////////////////////////////////////////////
  public DbTabTipoDoc getTipoDoc( Integer tipoDocId )
  {
    return bizCache.getTipoDoc( tipoDocId );
  }

  ///////////////////////////////////////////////////////////
  public java.util.List<DbTabTipoDoc> getTipoDocs()
  {
    return bizCache.getTipoDocs();
  }

  ////////////////////////////////////////////////////////////
  public DbTabTipoEnt getTipoEnt( Integer tipoEntId )
  {
    return bizCache.getTipoEnt( tipoEntId );
  }

  ///////////////////////////////////////////////////////////
  public java.util.List<DbTabTipoEnt> getTipoEnts()
  {
    return bizCache.getTipoEnts();
  }

  ///////////////////////////////////////////////////////////
  public DbTabTipoProd getTipoProd( Integer tipoProdId )
  {
    return bizCache.getTipoProd( tipoProdId );
  }
  
  ///////////////////////////////////////////////////////////
  public java.util.List<DbTabTipoProd> getTipoProds() 
  {
    return bizCache.getTipoProds();
  }
  
  ///////////////////////////////////////////////////////////////
  public DbTabUniMov getUniMov( Integer uniMovId )
  {
    return bizCache.getUniMov( uniMovId );
  }

  ///////////////////////////////////////////////////////////////
  public java.util.List<DbTabUniMov> getUniMovs()
  {
    return bizCache.getUniMovs();
  }

  ///////////////////////////////////////////////////////////
  public String getTipoEntName( int tipoEntId ) 
  {
    return bizCache.getTipoEntName( tipoEntId );
  }
  
  ///////////////////////////////////////////////////////////
  public String getTipoDocName( Integer tipoDocId )
  {
    return bizCache.getTipoDocName( tipoDocId );
  }
  
  ///////////////////////////////////////////////////////////
  private String getTipoDocNameQueryByTipoEntDoc()
  {
    String query =
      "select " + DbTabDocProps.FIELDS[ DbTabDocProps.DOC_NAME ] +
      " from " + DbTabDocProps.T_NAME + 
      " where " + 
        DbTabDocProps.FIELDS[ DbTabDocProps.TIPO_ENT_ID ] + " = ? and " +
        DbTabDocProps.FIELDS[ DbTabDocProps.TIPO_DOC_ID ] + " = ?";
    return query;
  }
  
  ///////////////////////////////////////////////////////////
  private String getTipoDocNameQueryByTipoDoc()
  {
    String query =
      "select " + DbTabTipoDoc.FIELDS[ DbTabTipoDoc.NOME ] +
      " from " + DbTabTipoDoc.T_NAME + 
      " where " + DbTabTipoDoc.FIELDS[ DbTabTipoDoc.TIPO_DOC_ID ] + " = ?";
    return query;
  }
  
//  ///////////////////////////////////////////////////////////
//  public String getTipoDocName( int tipoEntId, int tipoDocId )
//  throws SQLException
//  {
//    Database database = MpAppContext.getInstance().getDatabase();
//    String docName = null;
//    String query = getTipoDocNameQueryByTipoEntDoc();
//    PreparedStatement ps = database.getPreparedStatement( query );
//    ps.setInt( 1, tipoEntId );
//    ps.setInt( 2, tipoDocId );
//    ResultSet rs = ps.executeQuery();
//    if( rs.next() )
//    {
//      docName = rs.getString( 1 );
//    }
//    rs.close();
//    ps.close();
//    if( docName.trim().length() == 0 )
//    {
//      query = getTipoDocNameQueryByTipoDoc();
//      ps = database.getPreparedStatement( query );
//      ps.setInt( 1, tipoEntId );
//      rs = ps.executeQuery();
//      if( rs.next() )
//      {
//        docName = rs.getString( 1 );
//      }
//      rs.close();
//      ps.close();
//    }
//    return docName;
//  }
  ///////////////////////////////////////////////////////////////
  public Integer getDocLinType( Integer tipoDocId )
  {
    return bizCache.getDocLinType( tipoDocId );
  }
  
  ///////////////////////////////////////////////////////////////
  String pstGetLastDocNumber =
    "select " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + ", " +
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + 
    " from " + DbDoc.T_NAME +
    " where " + 
    DbDoc.FIELDS[ DbDoc.TIPO_ENT_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + " > 0" +
    " order by " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + " desc";

  String pstGetLastDocNumberByYear =
    "select " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + ", " +
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + 
    " from " + DbDoc.T_NAME +
    " where " + 
    DbDoc.FIELDS[ DbDoc.TIPO_ENT_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + " > 0 and " +
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + " >= ? and " + 
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + " <= ?" +
    " order by " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + " desc";

  ///////////////////////////////////////////////////////////////
  public Integer getLastDocNumber( Integer tipoEntId, Integer tipoDocId )
  throws SQLException, MpDocException
  {
    Integer docId = null;
    Database database = dbProvider.getDatabase();
    PreparedStatement ps = ps = database.getPreparedStatement( pstGetLastDocNumber );
    ps.setInt( 1, tipoEntId.intValue() );
    ps.setInt( 2, tipoDocId.intValue() );
    if( logger.isDebugEnabled() )
    {
      logger.debug( "query: " + ps.toString() );
    }
    
    ResultSet rs = ps.executeQuery();
    if ( rs.next() )
    {
      docId = rs.getInt( 1 );
    }
    ps.close();
    return docId;
  }
  
  ///////////////////////////////////////////////////////////////
  public int getLastDocNumber( MpDay day, Integer tipoEntId, Integer tipoDocId )
  throws SQLException, MpDocException, DatabaseException
  {
    Integer docId = 0;
    Database database = dbProvider.getDatabase();
    MpBizAppConfig docConfig = MpBizAppConfig.getInstance();
    int yearSuffixLen = docConfig.getYearSuffixLen( tipoEntId, tipoDocId );
    if( yearSuffixLen == 0 )
      return getLastDocNumberAbsolute( tipoEntId, tipoDocId );

    MpDay dayYear = new MpDay( day.getDate() );
    dayYear.setMonth( 1 );
    dayYear.setDay( 1 );

    MpDay lastDayYear = new MpDay( day.getDate() );
    lastDayYear.setMonth( 12 );
    lastDayYear.setDay( 31 );
    
    String prefix = "" + day.getYear();
    PreparedStatement ps = ps = database.getPreparedStatement( pstGetLastDocNumberByYear );
    ps.setInt( 1, tipoEntId.intValue() );
    ps.setInt( 2, tipoDocId.intValue() );
    ps.setDate( 3, dayYear.getSqlDate() );
    ps.setDate( 4, lastDayYear.getSqlDate() );
    if( logger.isDebugEnabled() )
    {
      logger.debug( "query: " + ps.toString() );
    }
    
    java.sql.Date docDate = null;
    ResultSet rs = ps.executeQuery();
    if ( rs.next() )
    {
      docId = rs.getInt( 1 );
      docDate = rs.getDate( 2 );
    }
    ps.close();
    if( docId == 0 )
    {
      docId = bizCache.getDocPropsStartNumber( tipoEntId, tipoDocId );
      Double dPrefix = Math.pow( 10, yearSuffixLen );
      Integer firstDoc = dPrefix.intValue() * day.getYear();
      docId += (dPrefix.intValue() * day.getYear());
    }
    return docId;
  }
  
  ///////////////////////////////////////////////////////////////
  public int getLastDocNumberAbsolute( Integer tipoEntId, Integer tipoDocId )
  throws SQLException, MpDocException, DatabaseException
  {
    int docId = 0;
    Database database = dbProvider.getDatabase();
    MpBizAppConfig docConfig = MpBizAppConfig.getInstance();
    PreparedStatement ps = database.getPreparedStatement( pstGetLastDocNumber );
    ps.setInt( 1, tipoEntId.intValue() );
    ps.setInt( 2, tipoDocId.intValue() );
    ResultSet rs = ps.executeQuery();
    if ( rs.next() )
    {
      docId = rs.getInt( 1 );
    }
    ps.close();
    if( docId == 0 )
    {
      docId = bizCache.getDocPropsStartNumber( tipoEntId, tipoDocId );
    }
    return docId;
  }
  
  ///////////////////////////////////////////////////////////////
  String pstGetLastDocDate =
    "select " +
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + 
    " from " + DbDoc.T_NAME +
    " where " + 
    DbDoc.FIELDS[ DbDoc.TIPO_ENT_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.TIPO_DOC_ID ] + " = ? and " +
    DbDoc.FIELDS[ DbDoc.DOC_ID ] + " > 0" +
    " order by " +
    DbDoc.FIELDS[ DbDoc.DATA_DOC ] + " desc";
  
  ///////////////////////////////////////////////////////////////
  public java.sql.Date getLastDocDate( Integer tipoEntId, Integer tipoDocId )
  throws SQLException
  {
    java.sql.Date dataDoc = null;
    Database database = dbProvider.getDatabase();
    PreparedStatement ps = 
      database.getPreparedStatement( pstGetLastDocDate );
    ps.setInt( 1, tipoEntId.intValue() );
    ps.setInt( 2, tipoDocId.intValue() );
    ResultSet rs = ps.executeQuery();
    if ( rs.next() )
    {
      dataDoc = rs.getDate( 1 );
    }
    ps.close();
    return dataDoc;
  }
  
//  ///////////////////////////////////////////////////////////////
//  public int getLastTmpDocNumber( 
//    DbFactory dbProvider, int tipoEntId, int tipoDocId )
//  throws SQLException
//  {
//    return getLastTmpDocNumber( 
//      new Integer( tipoEntId ), new Integer( tipoDocId ) );
//  }
//  
  ///////////////////////////////////////////////////////////////
  public int getLastTmpDocNumber( Integer tipoEntId, Integer tipoDocId )
  throws SQLException, XgmException
  {
    int docId = 0;
    DbDoc dbDoc = new DbDoc();
    String where =
      dbDoc.getSqlName( DbDoc.TIPO_ENT_ID ) + "=" + tipoEntId + " and " +
      dbDoc.getSqlName( DbDoc.TIPO_DOC_ID ) + "=" + tipoDocId + " and " +
      dbDoc.getSqlName( DbDoc.DOC_ID ) + "<0";
    String order = dbDoc.getPKeyOrder();
    Statement stmt =
      MpAppContext.getInstance().getDatabase().getConnection().createStatement();
    String query = 
      "select * from " + dbDoc.getTableName() + 
      " where " + where + " order by " + order;
    System.out.println( 
      "<MpDocFactory.getLastDocNumber>\n  tipoEnt: " + tipoEntId + 
      "\n  tipoDoc: " + tipoDocId +
      "\n  query: " + query );
    ResultSet rs = stmt.executeQuery( query );
    if ( rs.next() )
    {
      docId = rs.getInt( DbDoc.DOC_ID + 1 );
      System.out.println( 
        "<MpDocFactory.getLastDocNumber>\n  docId: " + docId );
      int dbTipoEntId = rs.getInt( DbDoc.TIPO_ENT_ID + 1 );
      System.out.println( 
        "<MpDocFactory.getLastDocNumber>\n  tipoEnt: " + dbTipoEntId );
      int dbTipoDocId = rs.getInt( DbDoc.TIPO_DOC_ID + 1 );
      System.out.println( 
        "<MpDocFactory.getLastDocNumber>\n  tipoDoc: " + dbTipoDocId );
      if( dbTipoEntId != tipoEntId.intValue() || 
          dbTipoDocId != tipoDocId.intValue() )
        docId = 0;
    }
    rs.close();
    stmt.close();
    System.out.println( 
      "<MpDocFactory.getLastDocNumber>\n  DocId: " + docId );
    return docId;
  }
  
  ///////////////////////////////////////////////////////////////
  public static java.util.List<Integer> getAllowedDocOrgTypes( 
    int tipoEntId, int tipoDocId ) 
  throws SQLException, DatabaseException, MpDocException
  {
    java.util.List<Integer> docTypes = 
      MpBizAppConfig.getInstance().getDocFlow( tipoEntId, tipoDocId );
    return docTypes;
  }
  
  ///////////////////////////////////////////////////////////////
  public static final Vector<ComboData> getCostCenterComboData( boolean insertEmpty ) 
  throws SQLException
  {
    Vector<ComboData> costCenters = 
      ComboData.getData(
        new DbCostCenter(), 
        DbCostCenter.COST_CENTER_ID, DbCostCenter.CC_NAME, insertEmpty );
    return costCenters;
  }


}
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.