diff --git a/trunk/PlanosActuacao/src/db/providers/EvoBaseProvider.java b/trunk/PlanosActuacao/src/db/providers/EvoBaseProvider.java new file mode 100644 index 00000000..e5cd20e0 --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/EvoBaseProvider.java @@ -0,0 +1,413 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.entity.ProviderInterface; +import com.evolute.entity.ProviderRegistry; +import com.evolute.entity.evo.EvoDataException; +import com.evolute.entity.evo.EvoDataObject; +import com.evolute.entity.evo.EvoDataProvider; +import com.evolute.entity.evo.EvoDataProviderFactory; +import com.evolute.entity.utils.ConnectionIdentity; +import com.evolute.utils.Singleton; +import com.evolute.utils.db.DBException; +import com.evolute.utils.db.DBManager; +import com.evolute.utils.db.Executer; +import com.evolute.utils.db.JDBCManager; +import com.evolute.utils.error.ErrorLogger; +import com.evolute.utils.jdbc.DBStatementExecuter; +import com.evolute.utils.jdbc.StatementExecuterFactory; +import com.evolute.utils.sql.SQLQuery; +import com.evolute.utils.sql.backend.BackendProvider; +import com.evolute.utils.strings.UnicodeChecker; +import db.DBConstants; +import db.DBPropertiesLoader; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.servlet.http.HttpSession; + +/** + * + * @author dneves + */ +public class EvoBaseProvider +{ + private static EvoBaseProvider INSTANCE = null; + + private ProviderInterface< EvoDataObject< ? >, EvoDataException > providerInterface; + private DBManager dbManager; + + private ProviderInterface< EvoDataObject< ? >, EvoDataException > localProviderInterface; + private DBManager localDBManager; + + private String url; + private String username; + private String password; + + private String url_local; + private String username_local; + private String password_local; + + + + private EvoBaseProvider() throws DBException + { + init(); + } + + public static synchronized EvoBaseProvider getInstance() throws DBException + { + if ( INSTANCE == null ) + { + INSTANCE = new EvoBaseProvider(); + } + return INSTANCE; + } + + private void init() throws DBException + { +// System.out.println( "EvoBaseProvider . init() : " ); + + String server = DBPropertiesLoader.getInstance().findProperty( DBConstants.SERVER_SIPRP ); + int port = DBPropertiesLoader.getInstance().findProperty( DBConstants.PORT_SIPRP, -1 ); + String dbname = DBPropertiesLoader.getInstance().findProperty( DBConstants.DATABASE_SIPRP ); + username = DBPropertiesLoader.getInstance().findProperty( DBConstants.USERNAME_SIPRP ); + password = DBPropertiesLoader.getInstance().findProperty( DBConstants.PASSWORD_SIPRP ); + +// System.out.println( "\t" + server + " : " + port + " : " + dbname + " : " + username + " : " + password ); + + String server_local = DBPropertiesLoader.getInstance().findProperty( DBConstants.SERVER_SIPRP_LOCAL ); + int port_local = DBPropertiesLoader.getInstance().findProperty( DBConstants.PORT_SIPRP_LOCAL, -1 ); + String dbname_local = DBPropertiesLoader.getInstance().findProperty( DBConstants.DATABASE_SIPRP_LOCAL ); + username_local = DBPropertiesLoader.getInstance().findProperty( DBConstants.USERNAME_SIPRP_LOCAL ); + password_local = DBPropertiesLoader.getInstance().findProperty( DBConstants.PASSWORD_SIPRP_LOCAL ); + +// System.out.println( "\t" + server_local + " : " + port_local + " : " + dbname_local + " : " + username_local + " : " + password_local ); + + init( DBConstants.DB.SIPRP, server, port, dbname, username, password ); + init( DBConstants.DB.SIPRP_LOCAL, server_local, port_local, dbname_local, username_local, password_local ); + } + + private void init( DBConstants.DB db, String dbServer, Integer dbPort, String dbName, String dbUsername, String dbPassword ) + throws DBException + { + String dbUrl = "jdbc:postgresql://" + dbServer + ":" + dbPort + "/" + dbName + "?prepareThreshold=2"; + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + Singleton.setInstance( DBConstants.CONNECTION_URL, dbUrl ); + url = dbUrl; + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + Singleton.setInstance( DBConstants.LOCAL_CONNECTION_URL, dbUrl ); + url_local = dbUrl; + } + + createDBManager( db, dbUsername, dbPassword ); + initProviderConnection( db, dbUsername, dbPassword ); + } + + private void createDBManager( DBConstants.DB db, String username, String password ) + throws DBException + { + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + if( dbManager != null ) + { + dbManager.close(); + } + String dbUrl = ( String ) Singleton.getInstance( DBConstants.CONNECTION_URL ); + DBManager manager = new JDBCManager( dbUrl, username, password , 14, 7, 7, new SQLQuery[] { } ); + StatementExecuterFactory.initialize( new DBStatementExecuter( manager.getSharedExecuter( EvoBaseProvider.class ) ) ); + UnicodeChecker.setUseDoubleSlash( true ); +// Insert.setDefaultKeyRetriever( PostgresqlAutoKeyRetriever.RETRIEVER ); + dbManager = manager; +// Singleton.setInstance( Singleton.DEFAULT_DBMANAGER, dbManager ); +// System.out.println( "\nDBManager : " + dbManager ); + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + if( localDBManager != null ) + { + localDBManager.close(); + } + String dbUrl = ( String ) Singleton.getInstance( DBConstants.LOCAL_CONNECTION_URL ); + DBManager manager = new JDBCManager( dbUrl, username, password , 14, 7, 7, new SQLQuery[] { } ); + StatementExecuterFactory.initialize( new DBStatementExecuter( manager.getSharedExecuter( EvoBaseProvider.class ) ) ); + UnicodeChecker.setUseDoubleSlash( true ); +// Insert.setDefaultKeyRetriever( PostgresqlAutoKeyRetriever.RETRIEVER ); + localDBManager = manager; + Singleton.setInstance( Singleton.DEFAULT_DBMANAGER, localDBManager ); +// System.out.println( "\nLocalDBManager : " + localDBManager ); + } + } + + private void initProviderConnection( DBConstants.DB db, String username, String password ) + { + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + String dbUrl = ( String ) Singleton.getInstance( DBConstants.CONNECTION_URL ); + providerInterface = createInstance( db, dbUrl, username, password ); + BackendProvider.getBackend( dbUrl ).setEscapeUnicode( false ); + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + String dbUrl = ( String ) Singleton.getInstance( DBConstants.LOCAL_CONNECTION_URL ); + localProviderInterface = createInstance( db, dbUrl, username, password ); + } + } + + private static ProviderInterface< EvoDataObject< ? >, EvoDataException > createInstance( DBConstants.DB db, String url, String user, String password ) + { + ProviderRegistry.registerDefaultProviderFactory( new EvoDataProviderFactory() ); + ConnectionIdentity conn = new ConnectionIdentity( url, user ); + ProviderRegistry.registerDefaultConnection( conn ); + ProviderInterface< EvoDataObject< ? >, EvoDataException > provider = + ( ProviderInterface< EvoDataObject< ? >, EvoDataException > ) ProviderRegistry.getDefaultProvider( conn ); + ( ( EvoDataProvider ) provider ).setIsUsingCache( Boolean.FALSE ); + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + Singleton.setInstance( DBConstants.DEFAULT_PROVIDER, provider ); + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + Singleton.setInstance( DBConstants.LOCAL_PROVIDER, provider ); + Singleton.setInstance( Singleton.DEFAULT_EVO_DATA_PROVIDER, provider ); + Singleton.setInstance( Singleton.DEFAULT_OBJECT_PROVIDER, provider ); + } + conn.setPassword( password ); + return provider; + } + + public ProviderInterface< EvoDataObject< ? >, EvoDataException > getProvider() + { + return getProvider( DBConstants.DB.SIPRP ); + } + + public ProviderInterface< EvoDataObject< ? >, EvoDataException > getProvider( DBConstants.DB db ) + { + ProviderInterface< EvoDataObject< ? >, EvoDataException > provider = null; + + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + provider = providerInterface; + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + provider = localProviderInterface; + } + + return provider; + } + + public DBManager getDbManager() + { + return getDbManager( DBConstants.DB.SIPRP ); + } + + public DBManager getDbManager( DBConstants.DB db ) + { + DBManager manager = null; + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + manager = dbManager; + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + manager = localDBManager; + } + return manager; + } + + public Executer getExecuter() throws DBException + { + return getExecuter( this ); + } + + private Executer getExecuter( Object clazz ) throws DBException + { + if ( getDbManager() == null ) + { + init(); + } + +// DBManager dbm = ( DBManager ) Singleton.getInstance( DBConstants.DEFAULT_DBMANAGER ); +// return dbm.getSharedExecuter( this ); + + DBManager dbm = getDbManager( DBConstants.DB.SIPRP ); + if ( dbm != null ) + { + return dbm.getSharedExecuter( this ); + } + return null; + } + + public Executer getLocalExecuter() throws DBException + { + return getLocalExecuter( this ); + } + + private Executer getLocalExecuter( Object clazz ) throws DBException + { + if ( getDbManager( DBConstants.DB.SIPRP_LOCAL ) == null ) + { + init(); + } +// DBManager dbm = ( DBManager ) Singleton.getInstance( DBConstants.LOCAL_DBMANAGER ); +// return dbm.getSharedExecuter( this ); + + DBManager dbm = getDbManager( DBConstants.DB.SIPRP_LOCAL ); + if ( dbm != null ) + { + return dbm.getSharedExecuter( this ); + } + return null; + } + + @Deprecated + public Statement createStatement() + { + String connectionURL = ( String ) Singleton.getInstance( DBConstants.CONNECTION_URL ); + String username = DBPropertiesLoader.getInstance().findProperty( DBConstants.USERNAME_SIPRP ); + String password = DBPropertiesLoader.getInstance().findProperty( DBConstants.PASSWORD_SIPRP ); + + return getStatement( DBConstants.DB.SIPRP, connectionURL, username, password ); + } + + @Deprecated + public Statement createLocalStatement() + { + String connectionURL = ( String ) Singleton.getInstance( DBConstants.LOCAL_CONNECTION_URL ); + String username = DBPropertiesLoader.getInstance().findProperty( DBConstants.USERNAME_SIPRP_LOCAL ); + String password = DBPropertiesLoader.getInstance().findProperty( DBConstants.PASSWORD_SIPRP_LOCAL ); + + return getStatement( DBConstants.DB.SIPRP_LOCAL, connectionURL, username, password ); + } + + private Statement getStatement( DBConstants.DB db, String connectionURL, String username, String password ) + { + Statement stm = null; + try + { + Connection connection = getConnection( db, connectionURL, username, password ); + if ( connection != null ) + { + stm = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); + } + } + catch ( Exception e ) + { + ErrorLogger.logException( e ); + } + return stm; + } + + private Connection getConnection( DBConstants.DB db, String connectionURL, String username, String password ) throws Exception + { + Connection connection = null; +// System.out.println( "\nEvoBaseProvider . getConnection( " + connectionURL + ", " + username + " ) : " ); + + FacesContext fc = FacesContext.getCurrentInstance(); +// System.out.println( "\tFacesContext : " + fc ); + if ( fc != null ) + { + + ExternalContext ec = fc.getExternalContext(); + // System.out.println( "\tExternalContext : " + ec ); + if ( ec != null ) + { + HttpSession session = ( HttpSession ) ec.getSession( false ); + // System.out.println( "\tSession : " + session ); + + if ( session != null ) + { + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + connection = ( Connection ) session.getAttribute( DBConstants.SESSION_CONNECTION ); + if ( connection == null ) + { + // System.out.println( "\n-> Creating new SIPRP connection ..." ); + Class.forName( "org.postgresql.Driver" ).newInstance(); + connection = DriverManager.getConnection( connectionURL, username, password ); + session.setAttribute( DBConstants.SESSION_CONNECTION, connection ); + } + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + connection = ( Connection ) session.getAttribute( DBConstants.SESSION_CONNECTION_LOCAL ); + if ( connection == null ) + { + // System.out.println( "\n-> Creating new SIPRP_LOCAL connection ..." ); + Class.forName( "org.postgresql.Driver" ).newInstance(); + connection = DriverManager.getConnection( connectionURL, username, password ); + session.setAttribute( DBConstants.SESSION_CONNECTION_LOCAL, connection ); + } + } + } + } + } + + if ( connection == null ) + { + connection = ( Connection ) Singleton.getInstance( "CONNECTION_OBJECT" ); + if ( connection == null ) + { + // System.out.println( "\nEvoBaseProvider . getConnection() : session is null !" ); + + if ( DBConstants.DB.SIPRP.equals( db ) ) + { + // System.out.println( "\t-> Creating new SIPRP connection ..." ); + Class.forName( "org.postgresql.Driver" ).newInstance(); + connection = DriverManager.getConnection( connectionURL, username, password ); + } + else if ( DBConstants.DB.SIPRP_LOCAL.equals( db ) ) + { + // System.out.println( "\t-> Creating new SIPRP_LOCAL connection ..." ); + Class.forName( "org.postgresql.Driver" ).newInstance(); + connection = DriverManager.getConnection( connectionURL, username, password ); + } + Singleton.setInstance( "CONNECTION_OBJECT", connection ); + } + } + +// System.out.println( "<-- getConnection() : " + connection ); + return connection; + } + + public String getUrl() + { + return url; + } + + public String getUsername() + { + return username; + } + + public String getPassword() + { + return password; + } + + public String getUrl_local() + { + return url_local; + } + + public String getUsername_local() + { + return username_local; + } + + public String getPassword_local() + { + return password_local; + } +} diff --git a/trunk/PlanosActuacao/src/db/providers/GenericDataProvider.java b/trunk/PlanosActuacao/src/db/providers/GenericDataProvider.java new file mode 100644 index 00000000..0da93335 --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/GenericDataProvider.java @@ -0,0 +1,122 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.entity.ProviderInterface; +import com.evolute.entity.evo.EvoDataException; +import com.evolute.entity.evo.EvoDataObject; +import com.evolute.utils.db.DBException; +import com.evolute.utils.db.Executer; +import com.evolute.utils.error.ErrorLogger; +import db.DBConstants; +import java.sql.ResultSet; +import java.sql.Statement; + + +public abstract class GenericDataProvider +{ + private ProviderInterface< EvoDataObject< ? >, EvoDataException > provider = null; + private Executer executer = null; + + private ProviderInterface< EvoDataObject< ? >, EvoDataException > localProvider = null; + private Executer localExecuter = null; + + protected GenericDataProvider() throws Exception + { + provider = EvoBaseProvider.getInstance().getProvider( DBConstants.DB.SIPRP ); + executer = EvoBaseProvider.getInstance().getExecuter(); + + localProvider = EvoBaseProvider.getInstance().getProvider( DBConstants.DB.SIPRP_LOCAL ); + localExecuter = EvoBaseProvider.getInstance().getLocalExecuter(); + } + + public Executer getExecuter() + { + return executer; + } + + public Executer getLocalExecuter() + { + return localExecuter; + } + + public ProviderInterface< EvoDataObject< ? >, EvoDataException > getProvider() + { + return provider; + } + + public ProviderInterface< EvoDataObject< ? >, EvoDataException > getLocalProvider() + { + return localProvider; + } + + +// public void checkConnection() +// { +// Db db = Db.getInstance(); +// if ( db.getConnection() == null ) +// { +// try +// { +// db.connect(); +// } +// catch ( Exception ex ) +// { +// ErrorLogger.logException( ex ); +// } +// } +// } + + protected Integer getMaxTableId(String table) + { + Statement st = createStatement(); + String id = table + ".id"; + String sql = "SELECT max(" + id + ")+1 AS MAXID FROM " + table; + try + { + ResultSet rs = st.executeQuery(sql); + rs.first(); + Integer newId = new Integer(rs.getInt("MAXID")); + if(newId.intValue() == 0) + { + newId = new Integer(1); + } + return newId; + } + catch(Exception ex) + { + return new Integer(1); + } + } + + protected Statement createStatement() + { + try + { +// Db db = Db.getInstance(); +// return db.createStatement(); + return EvoBaseProvider.getInstance().createStatement(); + } + catch ( DBException ex ) + { + ErrorLogger.logException( ex ); + } + return null; + } + + protected Statement createLocalStatement() + { + try + { + return EvoBaseProvider.getInstance().createLocalStatement(); + } + catch ( DBException ex ) + { + ErrorLogger.logException( ex ); + } + return null; + } +} diff --git a/trunk/PlanosActuacao/src/db/providers/PlanosDataProvider.java b/trunk/PlanosActuacao/src/db/providers/PlanosDataProvider.java new file mode 100644 index 00000000..b3956060 --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/PlanosDataProvider.java @@ -0,0 +1,1296 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.utils.arrays.Virtual2DArray; +import com.evolute.utils.data.Mappable; +import com.evolute.utils.data.MappableObject; +import com.evolute.utils.error.ErrorLogger; +import com.evolute.utils.sql.Assignment; +import com.evolute.utils.sql.Expression; +import com.evolute.utils.sql.Field; +import com.evolute.utils.sql.Select; +import com.evolute.utils.sql.Select2; +import com.evolute.utils.sql.Update; +import com.evolute.utils.sql.expression.Par; +import com.evolute.utils.strings.StringPlainer; +import db.data.siprp.outer.EstabelecimentosData; +import db.data.siprp.outer.EstadoMedidasData; +import db.data.siprp.outer.PlanoAreasData; +import db.data.siprp.outer.PlanoMedidasData; +import db.data.siprp.outer.PlanoPostosTrabalhoData; +import db.data.siprp.outer.PlanoRiscosData; +import db.data.siprp.outer.PlanoValoresQualitativosData; +import db.data.siprp.outer.PlanosActuacaoData; +import db.entidades.Area; +import db.entidades.EstadoMedida; +import db.entidades.LinhaEstatistica; +import db.entidades.Medida; +import db.entidades.PlanoActuacao; +import db.entidades.PostoTrabalho; +import db.entidades.Risco; +import db.entidades.Utilizador; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import utils.Global; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import utils.Utils; + + +public class PlanosDataProvider extends GenericDataProvider +{ + private static PlanosDataProvider INSTANCE = null; + protected static final String UNCONTROLLED = "Incontrolado"; + protected static final String CONTROLLED = "Controlado"; + protected static final String INDETERMINATE = "Indeterminado"; + protected static final String NAO_VALORAVEL = "N\u00E3o Valor\u00E1vel"; + protected static final String NAO_VALORAVEL_SHORT = "N/V"; + protected static final String MUITO_ALTO = "Muito Alto"; + protected static final String ALTO = "Alto"; + protected static final String MEDIO = "M\u00e9dio"; + protected static final String BAIXO = "Baixo"; + + protected HashMap VALORES_QUALITATIVOS_BY_ID = new HashMap(); + + private PlanosDataProvider() throws Exception + { + super(); + } + + public static synchronized PlanosDataProvider getInstance() throws Exception + { + if ( INSTANCE == null ) + { + INSTANCE = new PlanosDataProvider(); + } + return INSTANCE; + } + + public void updatePlano( PlanoActuacao p ) throws Exception + { + if ( p.getConcluidoPorDesactivacao() == null ) + { + p.setConcluidoPorDesactivacao( false ); + } + if ( p.getObs_correcao() == null ) + { + p.setObs_correcao( "" ); + } + if ( p.getObservacoes_dl() == null ) + { + p.setObservacoes_dl( "" ); + } + if ( p.getObservacoes_dns() == null ) + { + p.setObservacoes_dns( "" ); + } + if ( p.getUser_dir_loja() != null && p.getUser_dir_loja().intValue() == 0 ) + { + p.setUser_dir_loja( null ); + } + if ( p.getUser_dns() != null && p.getUser_dns().intValue() == 0 ) + { + p.setUser_dns( null ); + } + if ( p.getUser_hs() != null && p.getUser_hs().intValue() == 0 ) + { + p.setUser_hs( null ); + } + if ( p.getUser_seg() != null && p.getUser_seg().intValue() == 0 ) + { + p.setUser_seg( null ); + } + + Expression where = new Field( "id" ).isEqual( p.getId() ); + + Update upd = new Update( "planos_actuacao", new Assignment[] + { + new Assignment( new Field( "fase" ), p.getFase() ), + new Assignment( new Field( "validacao_director_loja" ), p.getValidacao_director_loja() ), + new Assignment( new Field( "validacao_dns" ), p.getValidacao_dns() ), + new Assignment( new Field( "validacao_hs" ), p.getValidacao_hs() ), + new Assignment( new Field( "observacoes_dl" ), p.getObservacoes_dl() ), + new Assignment( new Field( "observacoes_dns" ), p.getObservacoes_dns() ), + new Assignment( new Field( "obs_correcao" ), p.getObs_correcao() ), + new Assignment( new Field( "correcao" ), p.getCorrecao() ), + new Assignment( new Field( "fase_antes_correcao" ), p.getFase_antes_correcao() ), + new Assignment( new Field( "concluido_por_desactivacao" ), ( p.getConcluidoPorDesactivacao() == null ? new Boolean( false ) : p.getConcluidoPorDesactivacao() ) ), + new Assignment( new Field( "data_desactivacao" ), p.getDataDesactivacao() ), + new Assignment( new Field( "data_validacao_dir_loja" ), p.getData_validacao_dir_loja() ), + new Assignment( new Field( "user_dir_loja" ), p.getUser_dir_loja() ), + new Assignment( new Field( "data_validacao_dns" ), p.getData_validacao_dns() ), + new Assignment( new Field( "user_dns" ), p.getUser_dns() ), + new Assignment( new Field( "data_validacao_hs" ), p.getData_validacao_hs() ), + new Assignment( new Field( "user_hs" ), p.getUser_hs() ), + new Assignment( new Field( "data_controlo" ), p.getData_controlo() ), + new Assignment( new Field( "data_email_controlo" ), p.getData_email_controlo() ), + new Assignment( new Field( "data_validacao_seg" ), p.getData_validacao_seg() ), + new Assignment( new Field( "user_seg" ), p.getUser_seg() ) + }, where ); + + System.out.println( "SQL UPDATE PLANO : " + upd.toString() ); + + ErrorLogger.log( "SAVE : PlanosDataProvider.updatePlano( " + p.getId() + " ) : " + upd.toString() ); + getExecuter().executeQuery( upd ); + } + + public void updateRisco( Risco r ) throws Exception + { + if ( r.getResponsavel_execucao() == null ) + { + r.setResponsavel_execucao( "" ); + } + if ( r.getPor() == null ) + { + r.setPor( "" ); + } + if ( r.getRecursos_necessarios() == null ) + { + r.setRecursos_necessarios( "" ); + } + if ( r.getParecer_dl() == null ) + { + r.setParecer_dl( "" ); + } + if ( r.getParecer_dns() == null ) + { + r.setParecer_dns( "" ); + } + if ( r.getVerificacao_siprp() == null ) + { + r.setVerificacao_siprp( "" ); + } + + Expression where = new Field( "id" ).isEqual( r.getId() ); + + Update upd = new Update( PlanoRiscosData.TABLENAME, new Assignment[] { + new Assignment( new Field( PlanoRiscosData.RESPONSAVEL_EXECUCAO ), r.getResponsavel_execucao() ), + new Assignment( new Field( PlanoRiscosData.POR ), r.getPor() ), + new Assignment( new Field( PlanoRiscosData.RECURSOS_NECESSARIOS ), r.getRecursos_necessarios() ), + new Assignment( new Field( PlanoRiscosData.DATA_INICIO ), r.getData_inicio() ), + new Assignment( new Field( PlanoRiscosData.DATA_FIM ), r.getData_fim() ), + new Assignment( new Field( PlanoRiscosData.PARECER_DNS ), r.getParecer_dns() ), + new Assignment( new Field( PlanoRiscosData.PARECER_DL ), r.getParecer_dl() ), + new Assignment( new Field( PlanoRiscosData.VERIFICACAO_SIPRP ), r.getVerificacao_siprp() ) + }, where ); + + ErrorLogger.log( "\nSAVE : PlanosDataProvider.updateRisco( " + r.getId() + " ) : " + upd.toString() ); + getExecuter().executeQuery( upd ); + System.out.println( "\n\tUPDATE RISCO SUCCESS !" ); + } + + public void updateMedidas( Risco risco ) throws Exception + { + List< Medida > medidas = risco.getMedidas(); + for ( Medida m : medidas ) + { + Integer emID = null; + if ( m.getValidarMedidaId() != null && m.getValidarMedidaId().intValue() != 0 ) + { + emID = m.getValidarMedidaId(); + } + + Expression where = new Field( "id" ).isEqual( m.getId() ).and( new Field( "risco_id" ).isEqual( risco.getId() ) ); + + Update upd = new Update( PlanoMedidasData.TABLENAME, new Assignment[] { + new Assignment( new Field( PlanoMedidasData.ESTADO_MEDIDAS_ID ), emID ) + }, where ); + + System.out.println( "SQL UPDATE MEDIDAS : " + upd.toString() ); + ErrorLogger.log( "SAVE : PlanosDataProvider.updateMedidas( " + risco.getId() + " ) : " + upd.toString() ); + getExecuter().executeQuery( upd ); + } + } + + + + +// private String getExpression( String nome, String estabelecimento, String dataVisita ) +// { +// String tables = "planos_actuacao"; +// String whereExpression = "planos_actuacao.deleted_date IS NULL "; +// +// if ( nome != null ) +// { +// nome = StringPlainer.convertString( nome.trim() ); +// nome = nome.replaceAll( " ", "%" ); +// whereExpression += "AND ( " + +// "plain_utf8( planos_actuacao.tecnico_hs_nome ) LIKE '%" + nome + "%' " + +// "OR plain_utf8( planos_actuacao.tecnico_superior_hs_nome ) LIKE '%" + nome + "%' " + +// ") "; +// } +// if ( estabelecimento != null ) +// { +// estabelecimento = StringPlainer.convertString( estabelecimento.trim() ); +// estabelecimento = estabelecimento.replaceAll( " ", "%" ); +// whereExpression += "AND plain_utf8( planos_actuacao.nome_estabelecimento ) LIKE '%" + estabelecimento + "%' "; +// } +// if ( dataVisita != null ) +// { +// whereExpression += "AND planos_actuacao.data_visita = '" + dataVisita + "' "; +// } +// +// return "SELECT * FROM " + tables + " WHERE " + whereExpression; +// } + + private enum SECTION { ACTIVOS, SEGUIMENTO, CONCLUIDOS; }; + + private Select2 getExpression( SECTION section, Utilizador u, String nome, String estabelecimento, String dataVisita, Integer ano ) + { + Expression where = getWhereExpression( nome, estabelecimento, dataVisita ); + Expression faseExpression = null; + switch ( section ) + { + case ACTIVOS : + faseExpression = getFaseActivos( u ); + break; + case SEGUIMENTO : + faseExpression = getFaseSeguimento( u ); + break; + case CONCLUIDOS : + faseExpression = getFaseConcluidos( u ); + break; + } + if ( faseExpression != null ) + { + where = where.and( faseExpression ); + } + if( ano != null && ano.intValue() > 0 && dataVisita == null ) + { + where = where.and( new Field( "EXTRACT( year FROM " + PlanosActuacaoData.DATA_VISITA_FULL + " )" ).isEqual( ano) ); + } + Select2 query = new Select2( + new String[] { PlanosActuacaoData.TABLENAME, PlanoAreasData.TABLENAME, PlanoRiscosData.TABLENAME }, + new Integer[] { Select2.JOIN_INNER, Select2.JOIN_INNER }, + new Expression[] { + new Field( PlanosActuacaoData.ID_FULL ).isEqual( new Field( PlanoAreasData.PLANO_ID_FULL ) ) , + new Field( PlanoAreasData.ID_FULL ).isEqual( new Field( PlanoRiscosData.AREA_ID_FULL ) ) + }, + new String[] { + PlanosActuacaoData.ESTABELECIMENTO_ID_FULL, + PlanosActuacaoData.FASE_FULL, + PlanosActuacaoData.DATA_VISITA_FULL, + "trim( " + PlanosActuacaoData.NOME_ESTABELECIMENTO_FULL +" )", + PlanosActuacaoData.VALIDACAO_DIRECTOR_LOJA_FULL, + PlanosActuacaoData.VALIDACAO_DNS_FULL, + PlanosActuacaoData.VALIDACAO_HS_FULL, + "trim( " + PlanosActuacaoData.PARECER_DNS_FULL + " )", + "trim( " + PlanosActuacaoData.OBS_CORRECAO_FULL + " )", + PlanosActuacaoData.DATA_VALIDACAO_DIR_LOJA_FULL, + PlanosActuacaoData.USER_DIR_LOJA_FULL, + PlanosActuacaoData.DATA_VALIDACAO_DNS_FULL, + PlanosActuacaoData.USER_DNS_FULL, + PlanosActuacaoData.DATA_VALIDACAO_HS_FULL, + PlanosActuacaoData.USER_HS_FULL, + PlanosActuacaoData.FASE_ANTES_CORRECAO_FULL, + PlanosActuacaoData.CORRECAO_FULL, + "trim( " + PlanosActuacaoData.OBSERVACOES_DL_FULL + " )", + "trim( " + PlanosActuacaoData.OBSERVACOES_DNS_FULL + " )", + "trim( " + PlanosActuacaoData.VERIFICACAO_SIPRP_FULL + " )", + PlanosActuacaoData.DATA_CONTROLO_FULL, + PlanosActuacaoData.DATA_EMAIL_CONTROLO_FULL, + PlanosActuacaoData.EMPRESA_ID_FULL, + "trim( " + PlanosActuacaoData.NOME_EMPRESA_FULL + " )", + PlanosActuacaoData.TECNICO_HS_ID_FULL, + "trim( " + PlanosActuacaoData.TECNICO_HS_NOME_FULL + " )", + PlanosActuacaoData.ID_FULL, + PlanosActuacaoData.DATA_RELATORIO_FULL, + PlanosActuacaoData.DELETED_DATE_FULL, + PlanosActuacaoData.CONCLUIDO_POR_DESACTIVACAO_FULL, + PlanosActuacaoData.TECNICO_SUPERIOR_HS_ID_FULL, + "trim( " + PlanosActuacaoData.TECNICO_SUPERIOR_HS_NOME_FULL + " )", + PlanosActuacaoData.DATA_DESACTIVACAO_FULL, + PlanosActuacaoData.DATA_DISPONIBILIZACAO_FULL, + PlanosActuacaoData.DATA_VALIDACAO_SEG_FULL, + PlanosActuacaoData.USER_SEG_FULL, + PlanosActuacaoData.HS_RELATORIO_ID_FULL, + "COUNT( DISTINCT " + PlanoRiscosData.IS_PATRIMONIAL_FULL + " ) > 1" + }, + where, + null, new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", + "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", + "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37" }, + null, null + ); + query.disableOrderFieldsVerification(); + return query; + } + + private Expression getWhereExpression( String nome, String estabelecimento, String dataVisita ) + { + Expression result = new Field( PlanosActuacaoData.DELETED_DATE_FULL ).isEqual( null ); + if ( nome != null ) + { + nome = StringPlainer.convertString( nome.trim() ); + nome = nome.replaceAll( " ", "%" ); + result = result.and( new Par( + new Field( "plain_utf8( " + PlanosActuacaoData.TECNICO_HS_NOME_FULL + " )" ).isLike( "%" + nome + "%" ) + .or( new Field( "plain_utf8( " + PlanosActuacaoData.TECNICO_SUPERIOR_HS_NOME_FULL + " )" ).isLike( "%" + nome + "%" ) ) + ) ); + } + if ( estabelecimento != null ) + { + estabelecimento = StringPlainer.convertString( estabelecimento.trim() ); + estabelecimento = estabelecimento.replaceAll( " ", "%" ); + result = result.and( new Field( "plain_utf8( " + PlanosActuacaoData.NOME_ESTABELECIMENTO_FULL + " )" ).isLike( "%" + estabelecimento + "%" ) ); + } + if ( dataVisita != null ) + { + result = result.and( new Field( PlanosActuacaoData.DATA_VISITA_FULL ).isEqual( dataVisita ) ); + } + return result; + } + + + public List< PlanoActuacao > searchPlanosActivos( Utilizador u, String nome, String estabelecimento, String dataVisita, Integer ano ) + throws Exception + { + System.out.println( "\nPlanosDataProvider . searchPlanosActivos() : " ); + + Select2 query = getExpression( SECTION.ACTIVOS, u, nome, estabelecimento, dataVisita, ano ); + System.out.println( "\tSQL : " + query ); + + Virtual2DArray array = getExecuter().executeQuery( query ); + return getFullPlanos( array ); + +// String sql = getExpression( nome, estabelecimento, dataVisita ); +// sql += " AND " + getFaseActivos( u ); +// Statement st = createStatement(); +// ResultSet rs = st.executeQuery( query ); +// return getFullPlanos( rs ); + } + + public List< PlanoActuacao > searchPlanosSeguimento( Utilizador u, String nome, String estabelecimento, String dataVisita, Integer ano ) + throws Exception + { + System.out.println( "\nPlanosDataProvider . searchPlanosSeguimento() : " ); + + Select2 query = getExpression( SECTION.SEGUIMENTO, u, nome, estabelecimento, dataVisita, ano ); + System.out.println( "\tSQL : " + query ); + + Virtual2DArray array = getExecuter().executeQuery( query ); + return getFullPlanos( array ); + +// String sql = getExpression( nome, estabelecimento, dataVisita ); +// sql += " AND " + getFaseSeguimento( u ); +// Statement st = createStatement(); +// ResultSet rs = st.executeQuery( sql ); +// return getFullPlanos( rs ); + } + + public List< PlanoActuacao > searchPlanosConcluidos( Utilizador u, String nome, String estabelecimento, String dataVisita, Integer ano ) + throws Exception + { + System.out.println( "\nPlanosDataProvider . searchPlanosConcluidos() : " ); + + Select2 query = getExpression( SECTION.CONCLUIDOS, u, nome, estabelecimento, dataVisita, ano ); + System.out.println( "\tSQL : " + query ); + + Virtual2DArray array = getExecuter().executeQuery( query ); + return getFullPlanos( array ); + +// String sql = getExpression( nome, estabelecimento, dataVisita ); +// sql += " AND " + getFaseConcluidos( u ); +// Statement st = createStatement(); +// ResultSet rs = st.executeQuery( sql ); +// return getFullPlanos( rs ); + } + + + + private Expression getFaseActivos( Utilizador u ) + { + Expression result = null; + int userType = u.getTipo().intValue(); + switch ( userType ) + { + case Global.TECNICO_HS : + result = new Par( + new Field( "fase" ).isEqual( new Integer( 1 ) ) + .or( new Field( "fase" ).isEqual( new Integer( 5 ) ) ) + ); + break; + case Global.RESPONSAVEL_SEGURANCA : + result = new Field( "fase" ).isEqual( new Integer( 2 ) ); + break; + case Global.DIRECTOR_LOJA : + result = new Field( "fase" ).isEqual( new Integer( 3 ) ); + break; + case Global.DIRECTOR_NACIONAL_SEGURANCA : + result = new Field( "fase" ).isEqual( new Integer( 4 ) ); + break; + } + if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS && userType != Global.DIRECTOR_NACIONAL_SEGURANCA ) + { + Expression expr = new Field( "estabelecimento_id" ).isEqual( new Integer( u.getEstabelecimento_id() ) ); + result = result == null ? expr : result.and( expr ); + } + return result; + } + +// private String getFaseActivos( Utilizador u ) +// { +// String sql = ""; +// int userType = u.getTipo().intValue(); +// switch ( userType ) +// { +// case Global.TECNICO_HS: +// sql += " AND (fase = 1 OR fase = 5)"; +// break; +// +// case Global.RESPONSAVEL_SEGURANCA: +// sql += " AND fase = 2"; +// break; +// +// case Global.DIRECTOR_LOJA: +// sql += " AND fase = 3"; +// break; +// +// case Global.DIRECTOR_NACIONAL_SEGURANCA: +// sql += " AND fase = 4"; +// break; +// } +// if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS && userType != Global.DIRECTOR_NACIONAL_SEGURANCA ) +// { +// sql += " AND estabelecimento_id = " + u.getEstabelecimento_id(); +// } +// +// return sql; +// } + +// private String getFaseSeguimento( Utilizador u ) +// { +// int userType = u.getTipo(); +// String sql = ""; +// switch( userType ) +// { +// case Global.TECNICO_HS: +// sql = " AND (fase <> 1 AND fase <> 5 AND fase <> 6) "; +// break; +// case Global.RESPONSAVEL_SEGURANCA: +// sql = " AND (fase <> 2 AND fase <> 6) "; +// break; +// case Global.DIRECTOR_LOJA: +// sql = " AND (fase <> 3 AND fase <> 6) "; +// break; +// case Global.DIRECTOR_NACIONAL_SEGURANCA: +// sql = " AND (fase <> 4 AND fase <> 6) "; +// break; +// case Global.DIRECTOR_SIPRP: +// case Global.RH: +// case Global.DIRECTOR_GERAL_RH: +// case Global.GESTOR: +// sql = " AND (fase > 1 AND fase < 6) "; +// break; +// default: +// break; +// } +// +// if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS +// && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH +// && userType != Global.GESTOR ) +// { +// sql += " AND estabelecimento_id = " + u.getEstabelecimento_id(); +// } +// if ( userType == Global.GESTOR ) +// { +// if ( u.getEstabelecimento_gestor().intValue() > 0 ) +// { +// sql += " AND estabelecimento_id = " + u.getEstabelecimento_gestor(); +// } +// } +// return sql; +// } + private Expression getFaseSeguimento( Utilizador u ) + { + Expression result = null; + int userType = u.getTipo().intValue(); + switch ( userType ) + { + case Global.TECNICO_HS : + result = new Par( + new Field( "fase" ).isDifferent( new Integer( 1 ) ) + .and( new Field( "fase" ).isDifferent( new Integer( 5 ) ) ) + .and( new Field( "fase" ).isDifferent( new Integer( 6 ) ) ) + ); + break; + case Global.RESPONSAVEL_SEGURANCA : + result = new Par( + new Field( "fase" ).isDifferent( new Integer( 2 ) ) + .and( new Field( "fase" ).isDifferent( new Integer( 6 ) ) ) + ); + break; + case Global.DIRECTOR_LOJA : + result = new Par( + new Field( "fase" ).isDifferent( new Integer( 3 ) ) + .and( new Field( "fase" ).isDifferent( new Integer( 6 ) ) ) + ); + break; + case Global.DIRECTOR_NACIONAL_SEGURANCA : + result = new Par( + new Field( "fase" ).isDifferent( new Integer( 4 ) ) + .and( new Field( "fase" ).isDifferent( new Integer( 6 ) ) ) + ); + break; + case Global.DIRECTOR_SIPRP : + case Global.RH : + case Global.DIRECTOR_GERAL_RH : + case Global.GESTOR : + result = new Par( + new Field( "fase" ).isGreater( new Integer( 1 ) ) + .and( new Field( "fase" ).isLess( new Integer( 6 ) ) ) + ); + break; + } + + if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS + && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH + && userType != Global.GESTOR ) + { + Expression expr = new Field( "estabelecimento_id" ).isEqual( u.getEstabelecimento_id() ); + result = result == null ? expr : result.and( expr ); + } + if ( userType == Global.GESTOR ) + { + if ( u.getEstabelecimento_gestor().intValue() > 0 ) + { + Expression expr = new Field( "estabelecimento_id" ).isEqual( u.getEstabelecimento_gestor() ); + result = result == null ? expr : result.and( expr ); + } + } + return result; + } + +// private String getFaseConcluidos( Utilizador u ) +// { +// int userType = u.getTipo().intValue(); +// String sql = " AND fase = 6 "; +// +// if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS +// && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH ) +// { +// sql += " AND estabelecimento_id = " + u.getEstabelecimento_id(); +// } +// +// return sql; +// } + private Expression getFaseConcluidos( Utilizador u ) + { + Expression result = new Field( "fase" ).isEqual( new Integer( 6 ) ); + int userType = u.getTipo().intValue(); + if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS + && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH + && userType != Global.GESTOR ) + { + result = result.and( new Field( "estabelecimento_id" ).isEqual( u.getEstabelecimento_id() ) ); + } + return result; + } + + + + private List< PlanoActuacao > getFullPlanos( Virtual2DArray array ) + { + List< PlanoActuacao > result = new LinkedList< PlanoActuacao >(); + if ( array != null ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer estabelecimentoID = array.get( i, 0 ); + Integer fase = array.get( i, 1 ); + Date dataVisita = array.get( i, 2 ); + String nomeEstabelecimento = array.get( i, 3 ); + Boolean validacaoDirectorLoja = array.get( i, 4 ); + Boolean validacaoDNS = array.get( i, 5 ); + Boolean validacaoHS = array.get( i, 6 ); + String parecerDNS = array.get( i, 7 ); + String observacaoCorreccao = array.get( i, 8 ); + Date dataValidacaoDirectorLoja = array.get( i, 9 ); + Integer userDirectorLoja = array.get( i, 10 ); + Date dataValidacaoDNS = array.get( i, 11 ); + Integer userDNS = array.get( i, 12 ); + Date dataValidacaoHS = array.get( i, 13 ); + Integer userHS = array.get( i, 14 ); + Integer faseAntesCorreccao = array.get( i, 15 ); + String correccao = array.get( i, 16 ); + String observacoesDL = array.get( i, 17 ); + String observacoesDNS = array.get( i, 18 ); + String verificacaoSIPRP = array.get( i, 19 ); + Date dataControlo = array.get( i, 20 ); + Date dataEmailControlo = array.get( i, 21 ); + Integer empresaID = array.get( i, 22 ); + String nomeEmpresa = array.get( i, 23 ); + Integer tecnicoHSID = array.get( i, 24 ); + String tecnicoHSNome = array.get( i, 25 ); + Integer id = array.get( i, 26 ); + Date dataRelatorio = array.get( i, 27 ); + Timestamp deletedStamp = array.get( i, 28 ); + Boolean concluidoPorDesactivacao = array.get( i, 29 ); + Integer tecnicoSuperiorHSID = array.get( i, 30 ); + String tecnicoSuperiorHSNome = array.get( i, 31 ); + Date dataDesactivacao = array.get( i, 32 ); + Date dataDisponibilizacao = array.get( i, 33 ); + Date dataValidacaoSeg = array.get( i, 34 ); + Integer userSeg = array.get( i, 35 ); + Integer hsRelatorioID = array.get( i, 36 ); + Boolean temPatrimoniais = array.get( i, 37 ); + + PlanoActuacao pa = new PlanoActuacao(); + pa.setId( id ); + pa.setEstabelecimento_id( estabelecimentoID ); + pa.setNome_estabelecimento( Utils.unicodeToHTML( nomeEstabelecimento ) ); + pa.setNome_empresa( Utils.unicodeToHTML( nomeEmpresa ) ); + pa.setFase( fase ); + pa.setData_visita( dataVisita ); + pa.setValidacao_director_loja( validacaoDirectorLoja ); + pa.setValidacao_dns( validacaoDNS ); + pa.setValidacao_hs( validacaoHS ); + pa.setObservacoes_dl( Utils.unicodeToHTML( observacoesDL ) ); + pa.setObservacoes_dns( Utils.unicodeToHTML( observacoesDNS ) ); + pa.setObs_correcao( Utils.unicodeToHTML( observacaoCorreccao ) ); + pa.setAreas( getAreasByPlanoID( id ) ); + pa.setTotal_riscos( getTotalRiscosByPlanoID( id ) ); + pa.setCorrecao( Utils.unicodeToHTML( correccao ) ); + pa.setFase_antes_correcao( faseAntesCorreccao ); + pa.setData_validacao_dir_loja( dataValidacaoDirectorLoja ); + pa.setUser_dir_loja( userDirectorLoja ); + pa.setData_validacao_dns( dataValidacaoDNS ); + pa.setUser_dns( userDNS ); + pa.setData_validacao_hs( dataValidacaoHS ); + pa.setUser_hs( userHS ); + pa.setTecnico_hs_id( tecnicoHSID ); + pa.setTecnico_hs_nome( Utils.unicodeToHTML( tecnicoHSNome ) ); + pa.setConcluidoPorDesactivacao( concluidoPorDesactivacao ); + pa.setDataDesactivacao( dataDesactivacao ); + pa.setTecnico_superior_hs_id( tecnicoSuperiorHSID ); + pa.setTecnico_superior_hs_nome( Utils.unicodeToHTML( tecnicoSuperiorHSNome ) ); + pa.setData_disponibilizacao( dataDisponibilizacao ); + pa.setData_validacao_seg( dataValidacaoSeg ); + pa.setUser_seg( userSeg ); + pa.setHs_relatorio_id( hsRelatorioID ); + pa.setTem_patrimoniais( temPatrimoniais ); + +// pa.setData_controlo( dataControlo ); +// pa.setData_email_controlo( dataEmailControlo ); +// pa.setEmpresa_id( empresaID ); +// pa.setData_relatorio( dataRelatorio ); + + result.add( pa ); + } + } + return result; + } + +// private List< PlanoActuacao > getFullPlanos( ResultSet rs ) throws Exception +// { +// List< PlanoActuacao > list = new LinkedList< PlanoActuacao >(); +// if ( rs.isBeforeFirst() ) +// { +// rs.first(); +// do +// { +// PlanoActuacao pa = new PlanoActuacao(); +// pa.setId( new Integer( rs.getInt("id") ) ); +// pa.setEstabelecimento_id( new Integer( rs.getInt( "estabelecimento_id" ) ) ); +// pa.setNome_estabelecimento( Utils.unicodeToHTML( rs.getString( "nome_estabelecimento" ) ) ); +// pa.setNome_empresa( Utils.unicodeToHTML( rs.getString( "nome_empresa" ) ) ); +// pa.setFase( new Integer( rs.getInt( "fase" ) ) ); +// java.sql.Date sqlDate = rs.getDate( "data_visita" ); +// pa.setData_visita( new java.util.Date( sqlDate.getTime() ) ); +// pa.setValidacao_director_loja( new Boolean( rs.getBoolean( "validacao_director_loja" ) ) ); +// pa.setValidacao_dns( new Boolean( rs.getBoolean("validacao_dns") ) ); +// pa.setValidacao_hs( new Boolean( rs.getBoolean("validacao_hs") ) ); +// pa.setObservacoes_dl( Utils.unicodeToHTML( rs.getString("observacoes_dl") ) ); +// pa.setObservacoes_dns( Utils.unicodeToHTML( rs.getString("observacoes_dns") ) ); +// pa.setObs_correcao( Utils.unicodeToHTML( rs.getString("obs_correcao") ) ); +// pa.setAreas( getAreasByPlano( pa ) ); +// pa.setTotal_riscos( getTotalRiscosByPlano( pa.getId() ) ); +// pa.setCorrecao( Utils.unicodeToHTML( rs.getString( "correcao") ) ); +// pa.setFase_antes_correcao( new Integer( rs.getInt( "fase_antes_correcao" ) ) ); +// pa.setData_validacao_dir_loja( rs.getDate( "data_validacao_dir_loja" ) ); +// pa.setUser_dir_loja( new Integer( rs.getInt( "user_dir_loja" ) ) ); +// pa.setData_validacao_dns( rs.getDate( "data_validacao_dns" ) ); +// pa.setUser_dns( new Integer( rs.getInt( "user_dns" ) ) ); +// pa.setData_validacao_hs( rs.getDate( "data_validacao_hs" ) ); +// pa.setUser_hs( new Integer( rs.getInt( "user_hs" ) ) ); +// pa.setTecnico_hs_id( new Integer( rs.getInt( "tecnico_hs_id" ) ) ); +// pa.setTecnico_hs_nome( Utils.unicodeToHTML( rs.getString("tecnico_hs_nome") ) ); +// pa.setConcluidoPorDesactivacao( new Boolean( rs.getBoolean( "concluido_por_desactivacao" ) ) ); +// pa.setDataDesactivacao( rs.getDate( "data_desactivacao" ) ); +// pa.setTecnico_superior_hs_id( new Integer( rs.getInt( "tecnico_superior_hs_id" ) ) ); +// pa.setTecnico_superior_hs_nome( Utils.unicodeToHTML( rs.getString( "tecnico_superior_hs_nome" ) ) ); +// pa.setData_disponibilizacao( rs.getDate( "data_disponibilizacao" ) ); +// pa.setData_validacao_seg( rs.getDate( "data_validacao_seg" ) ); +// pa.setUser_seg( rs.getInt( "user_seg" ) ); +// pa.setHs_relatorio_id( rs.getInt( "hs_relatorio_id" ) ); +// +// list.add( pa ); +// } +// while ( rs.next() ); +// } +// return list; +// } + + private List< Area > getAreasByPlanoID( final Integer planoID ) + { + List< Area > list = new LinkedList< Area >(); + try + { + Select2 query = new Select2( PlanoAreasData.TABLENAME, + new Field( PlanoAreasData.PLANO_ID_FULL ).isEqual( planoID ), + new String[] { PlanoAreasData.ID_FULL, PlanoAreasData.PLANO_ID_FULL, PlanoAreasData.DESCRICAO_FULL, + PlanoAreasData.ORDEM_FULL, PlanoAreasData.IS_PRINCIPAL_FULL }, + new String[] { PlanoAreasData.DESCRICAO_FULL } + ); + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null && array.columnLength() > 0 ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer areaID = array.get( i, 0 ); + Integer pID = array.get( i, 1 ); + String descricao = array.get( i, 2 ); + Integer ordem = array.get( i, 3 ); + Boolean isPrincipal = array.get( i, 4 ); + + Area area = new Area(); + area.setId( areaID ); + area.setPlano_id( pID ); + area.setDescricao( Utils.unicodeToHTML( descricao ) ); + area.setOrdem( ordem ); + area.setIs_principal( isPrincipal ); + area.setRiscos( getRiscosByArea( area ) ); + list.add( area ); + } + } + } + catch ( Exception e ) + { + ErrorLogger.logException( e ); + } + Collections.sort( list ); + return list; + } + + /** + * FIXME : ORDER BY patrimonial em ultimo ! + * + * @param a + * @return + * @throws Exception + */ + private List< Risco > getRiscosByArea( Area a ) throws Exception + { + List< Risco > list = new LinkedList< Risco >(); + + Select2 query = new Select2( + PlanoRiscosData.TABLENAME, + new Field( PlanoRiscosData.AREA_ID_FULL ).isEqual( a.getId() ), + new String[] { + PlanoRiscosData.ID_FULL, PlanoRiscosData.AREA_ID_FULL, PlanoRiscosData.DESCRICAO_FULL, PlanoRiscosData.RESPONSAVEL_EXECUCAO_FULL, + PlanoRiscosData.POR_FULL, PlanoRiscosData.RECURSOS_NECESSARIOS_FULL, PlanoRiscosData.DATA_INICIO_FULL, PlanoRiscosData.DATA_FIM_FULL, + PlanoRiscosData.PARECER_DL_FULL, PlanoRiscosData.PARECER_DNS_FULL, PlanoRiscosData.VERIFICACAO_SIPRP_FULL, PlanoRiscosData.VALOR_FULL, + PlanoRiscosData.IS_PATRIMONIAL_FULL, PlanoRiscosData.VALOR_QUALITATIVO_ID, "coalesce( valor, -1 ) AS ordem_valor", + }, + new String[] { "ordem_valor DESC", PlanoRiscosData.AREA_ID_FULL, PlanoRiscosData.RISCO_ID_FULL } + ); + query.disableOrderFieldsVerification(); + + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null && array.columnLength() > 0 ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer riscoID = array.get( i, 0 ); + Integer areaID = array.get( i, 1 ); + String descricao = array.get( i, 2 ); + String responsavelExecucao = array.get( i, 3 ); + String por = array.get( i, 4 ); + String recursosNecessarios = array.get( i, 5 ); + Date dataInicio = array.get( i, 6 ); + Date dataFim = array.get( i, 7 ); + String parecerDL = array.get( i, 8 ); + String parecerDNS = array.get( i, 9 ); + String verificacaoSiprp = array.get( i, 10 ); + Integer valor = array.get( i, 11 ); + Boolean isPatrimonial = array.get( i, 12 ); + Integer valorQualitativoID = array.get( i, 13 ); + + Risco r = new Risco(); + r.setId( riscoID ); + r.setArea_id( areaID ); + r.setDescricao( Utils.unicodeToHTML( descricao ) ); + r.setResponsavel_execucao( Utils.unicodeToHTML( responsavelExecucao ) ); + r.setPor( por ); + r.setRecursos_necessarios( Utils.unicodeToHTML( recursosNecessarios ) ); + r.setData_inicio( dataInicio ); + r.setData_fim( dataFim ); + r.setParecer_dl( Utils.unicodeToHTML( parecerDL ) ); + r.setParecer_dns( Utils.unicodeToHTML( parecerDNS ) ); + r.setVerificacao_siprp( Utils.unicodeToHTML( verificacaoSiprp ) ); + r.setValorQuantitativo( valor ); + r.setMedidas( getMedidasByRisco( r ) ); + r.setIsPatrimonial( isPatrimonial ); + r.setValorQualitativoID( valorQualitativoID ); + if( valorQualitativoID != null ) + { + r.setValorQualitativo( loadValorQualitativoByID( valorQualitativoID ).getDescricao() ); + } + list.add( r ); + } + } + Collections.sort( list, new Comparator(){ + + @Override + public int compare( Risco o1, Risco o2 ) + { + Integer o1Value = 1000; + Integer o2Value = 1000; + if( o1.getValorQuantitativo() != null ) + { + o1Value = -o1.getValorQuantitativo(); + } + else if(o1.getValorQualitativo() == null) + { + o1Value = 300; + } + else if(o1.getValorQualitativo().equals(UNCONTROLLED) || o1.getValorQualitativo().equals(MUITO_ALTO)) + { + o1Value = 100; + } + else if(o1.getValorQualitativo().equals(CONTROLLED) || o1.getValorQualitativo().equals(ALTO)) + { + o1Value = 200; + } + else if(o1.getValorQualitativo().equals(INDETERMINATE) || o1.getValorQualitativo().equals(MEDIO)) + { + o1Value = 300; + } + else if(o1.getValorQualitativo().equals(BAIXO)) + { + o1Value = 400; + } + if( o2.getValorQuantitativo() != null ) + { + o2Value = -o2.getValorQuantitativo(); + } + else if(o2.getValorQualitativo() == null ) + { + o2Value = 300; + } + else if(o2.getValorQualitativo().equals(UNCONTROLLED) || o2.getValorQualitativo().equals(MUITO_ALTO)) + { + o2Value = 100; + } + else if(o2.getValorQualitativo().equals(CONTROLLED) || o2.getValorQualitativo().equals(ALTO)) + { + o2Value = 200; + } + else if(o2.getValorQualitativo().equals(INDETERMINATE) || o2.getValorQualitativo().equals(MEDIO)) + { + o2Value = 300; + } + else if(o2.getValorQualitativo().equals(BAIXO)) + { + o2Value = 400; + } + return o1Value.compareTo(o2Value); + } + + } ); + return list; + } + + + private List< Medida > getMedidasByRisco( Risco r ) throws Exception + { + List< Medida > list = new LinkedList< Medida >(); + + Select2 query = new Select2( PlanoMedidasData.TABLENAME, + new Field( PlanoMedidasData.RISCO_ID_FULL ).isEqual( r.getId() ), + new String[] { + PlanoMedidasData.ID_FULL, PlanoMedidasData.DESCRICAO_FULL, PlanoMedidasData.ESTADO_MEDIDAS_ID_FULL + }, + new String[] { PlanoMedidasData.ID_FULL } + ); + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer planoMedidaID = array.get( i, 0 ); + String descricao = array.get( i, 1 ); + Integer estado = array.get( i, 2 ); + + Medida m = new Medida(); + m.setId( planoMedidaID ); + m.setDescricao( Utils.unicodeToHTML( descricao ) ); + m.setValidarMedidaId( estado ); + m.setPostos( getPostosByMedida( m ) ); + + list.add( m ); + } + } + + return list; + } + + private List< PostoTrabalho > getPostosByMedida( Medida m ) throws Exception + { + List< PostoTrabalho > list = new LinkedList< PostoTrabalho >(); + + Select2 query = new Select2( PlanoPostosTrabalhoData.TABLENAME, + new Field( PlanoPostosTrabalhoData.MEDIDA_ID_FULL ).isEqual( m.getId() ), + new String[] { PlanoPostosTrabalhoData.ID_FULL, PlanoPostosTrabalhoData.MEDIDA_ID_FULL, + PlanoPostosTrabalhoData.DESCRICAO_FULL, PlanoPostosTrabalhoData.IS_PRINCIPAL_FULL }, + new String[] { PlanoPostosTrabalhoData.ID_FULL } + ); + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer planoPostoTrabalhoID = array.get( i, 0 ); + Integer medidaID = array.get( i, 1 ); + String descricao = array.get( i, 2 ); + Boolean isPrincipal = array.get( i, 3 ); + + PostoTrabalho p = new PostoTrabalho(); + p.setId( planoPostoTrabalhoID ); + p.setMedida_id( medidaID ); + p.setDescricao( Utils.unicodeToHTML( descricao ) ); + p.setIs_principal( isPrincipal ); + list.add( p ); + } + } + + return list; + } + + private int getTotalRiscosByPlanoID( Integer planoID ) + { + int count = 0; + try + { + Select2 query = new Select2( + new String[] { PlanoRiscosData.TABLENAME, PlanoAreasData.TABLENAME, PlanosActuacaoData.TABLENAME }, + new Integer[] { Select2.JOIN_INNER, Select2.JOIN_INNER }, + new Expression[] { + new Field( PlanoRiscosData.AREA_ID_FULL ).isEqual( new Field( PlanoAreasData.ID_FULL ) ), + new Field( PlanoAreasData.PLANO_ID_FULL ).isEqual( new Field( PlanosActuacaoData.ID_FULL ) ) + }, + new String[] { + "COUNT( " + PlanoRiscosData.ID_FULL + " ) AS total_riscos" + }, + new Field( PlanosActuacaoData.ID_FULL ).isEqual( planoID ).and( + new Field( PlanosActuacaoData.DELETED_DATE_FULL ).isEqual( null ) + ), + new String[] {}, + null, + null, + null + ); + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null && array.columnLength() > 0 ) + { + Long countL = array.get( 0, 0 ); + count = countL == null ? 0 : countL.intValue(); + } + } + catch ( Exception e ) + { + ErrorLogger.logException( e ); + } + return count; + } + + public List< EstadoMedida > getEstadoMedidas() throws Exception + { + List< EstadoMedida > list = new LinkedList< EstadoMedida >(); + + Select2 query = new Select2( EstadoMedidasData.TABLENAME, + new Field( EstadoMedidasData.ACTIVO_FULL ).isEqual( "y" ), + new String[] { + EstadoMedidasData.ID_FULL, EstadoMedidasData.DESCRICAO_FULL, EstadoMedidasData.ORDEM_FULL, + EstadoMedidasData.ACTIVO_FULL + }, + new String[] { EstadoMedidasData.ORDEM_FULL + " ASC" } + ); + Virtual2DArray array = getExecuter().executeQuery( query ); + if ( array != null ) + { + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer estadoID = array.get( i, 0 ); + String descricao = array.get( i, 1 ); + Integer ordem = array.get( i, 2 ); + String activo = array.get( i, 3 ); + + EstadoMedida estado = new EstadoMedida(); + estado.setId( estadoID ); + estado.setDescricao( Utils.unicodeToHTML( descricao ) ); + list.add( estado ); + } + } + return list; + } + +// public HsRelatorioRiscoValorQualitativoData loadValorQualitativoByID( Integer valorID ) throws Exception +// { +// return getLocalProvider().load( HsRelatorioRiscoValorQualitativoData.class, valorID, HsRelatorioRiscoValorQualitativoData.ID ); +// } + + public void loadValoresQualitativos() throws Exception + { + VALORES_QUALITATIVOS_BY_ID.clear(); + List valores = getAllValoresQualitativos(); + for( PlanoValoresQualitativosData valor : valores ) + { + VALORES_QUALITATIVOS_BY_ID.put( valor.getId(), valor); + } + } + + public List getAllValoresQualitativos() throws Exception + { + return getProvider().listLoad( PlanoValoresQualitativosData.class, PlanoValoresQualitativosData.ID ); + } + + public PlanoValoresQualitativosData loadValorQualitativoByID( Integer valorID ) throws Exception + { +// return getProvider().load( PlanoValoresQualitativosData.class, valorID, PlanoValoresQualitativosData.ID ); + if( !VALORES_QUALITATIVOS_BY_ID.containsKey( valorID) ) + { + loadValoresQualitativos(); + } + return VALORES_QUALITATIVOS_BY_ID.get( valorID ); + } + + public List getDistinctYears( Integer excludeYear ) throws Exception + { + List result = new LinkedList(); + + Expression where = new Field( "deleted_date" ).isEqual( null ); + if ( excludeYear != null ) + { + where = where.and( new Field( "EXTRACT( year FROM data_visita )" ).notIn( new Integer[] { excludeYear } ) ); + } + Select2 query = new Select2( + new String[] { "planos_actuacao" }, + new Integer[] { }, + new Expression[] { }, + new String[] { "DISTINCT( cast( EXTRACT( year FROM data_visita ) as integer ) ) AS ano" }, + where, + new String[] { "ano DESC" }, + null, null, null ); + query.disableOrderFieldsVerification(); + Virtual2DArray array = getExecuter().executeQuery( query ); + for ( int i = 0; i < array.columnLength(); i++ ) + { + Integer ano = array.get( i, 0 ); + result.add( ano ); + } + return result; + } + + public List getEstatisticaForPlanoId( Integer planoId ) + throws Exception + { + Select select = + new Select2( new String[]{ PlanoAreasData.TABLENAME, PlanoRiscosData.TABLENAME, PlanoMedidasData.TABLENAME, + EstadoMedidasData.TABLENAME, PlanoValoresQualitativosData.TABLENAME }, + new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_LEFT_OUTER, Select2.JOIN_LEFT_OUTER }, + new Expression[]{ + new Field( PlanoAreasData.ID_FULL ).isEqual( new Field( PlanoRiscosData.AREA_ID_FULL ) ), + new Field( PlanoRiscosData.ID_FULL ).isEqual( new Field( PlanoMedidasData.RISCO_ID_FULL ) ), + new Field( EstadoMedidasData.ID_FULL ).isEqual( new Field( PlanoMedidasData.ESTADO_MEDIDAS_ID_FULL ) ), + new Field( PlanoValoresQualitativosData.ID_FULL ).isEqual( new Field( PlanoRiscosData.VALOR_QUALITATIVO_ID_FULL ) ), + }, + new String[]{ "COALESCE( " + EstadoMedidasData.DESCRICAO_FULL + ", 'n.d.' )", + "COALESCE( ''|| " + PlanoRiscosData.VALOR_FULL + "," + PlanoValoresQualitativosData.DESCRICAO_FULL + " )", + "COUNT( * )", + EstadoMedidasData.ORDEM_FULL, + PlanoRiscosData.VALOR_FULL }, + new Field( PlanoAreasData.PLANO_ID_FULL ).isEqual( planoId), + new String[]{ "4", "5", "2" }, + new String[]{ "1", "4", "2", "5" }, + null, + null ) ; + select.disableOrderFieldsVerification(); + Virtual2DArray array = getExecuter().executeQuery( select ); + List linhas = new ArrayList(); + int total = 0; + String last = null; + int totalEstado = 0; + for( int n = 0; n < array.columnLength(); n++ ) + { + String estado = array.get( n, 0 ); + if( last == null ? estado != null : !last.equals( estado ) ) + { + if( totalEstado > 0 ) + { + linhas.add( new LinhaEstatistica( "", "TOTAL", 0, totalEstado ) ); + } + last = estado; + totalEstado = 0; + } + else + { + estado = ""; + } + String valoracao = array.get( n, 1 ); + Integer count = ( ( Number ) array.get( n, 2 ) ).intValue(); + total += count; + totalEstado += count; + linhas.add( new LinhaEstatistica( estado, valoracao, 0, count) ); + } + linhas.add( new LinhaEstatistica( "", "TOTAL", 0, totalEstado ) ); + for( LinhaEstatistica linha : linhas ) + { + linha.setPercentagem( ( int ) Math.round( linha.getQuantidade().doubleValue() * 100.0 / (double) total ) ); + } + linhas.add( new LinhaEstatistica( "TOTAL", "", 100, total ) ); + return linhas; + } + + public List getEstatisticaForEstabelecimentoIdAndDateInterval( Integer estabelecimentoId, Date dataInicio, Date dataFim ) + throws Exception + { + Expression expr = null; + if( estabelecimentoId != null ) + { + expr = new Field( PlanosActuacaoData.ESTABELECIMENTO_ID_FULL ).isEqual( estabelecimentoId); + } + if( dataInicio != null ) + { + Expression diExpr = new Field( PlanosActuacaoData.DATA_VISITA_FULL ).isGreaterOrEqual( dataInicio); + if( expr != null ) + { + expr = expr.and( diExpr); + } + else + { + expr = diExpr; + } + } + if( dataFim != null ) + { + Expression dfExpr = new Field( PlanosActuacaoData.DATA_VISITA_FULL ).isLessOrEqual( dataFim); + if( expr != null ) + { + expr = expr.and( dfExpr); + } + else + { + expr = dfExpr; + } + } + Select select = + new Select2( new String[]{ PlanosActuacaoData.TABLENAME, PlanoAreasData.TABLENAME, PlanoRiscosData.TABLENAME, + PlanoMedidasData.TABLENAME, EstadoMedidasData.TABLENAME, PlanoValoresQualitativosData.TABLENAME }, + new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_LEFT_OUTER, Select2.JOIN_LEFT_OUTER }, + new Expression[]{ + new Field( PlanosActuacaoData.ID_FULL ).isEqual( new Field( PlanoAreasData.PLANO_ID_FULL ) ), + new Field( PlanoAreasData.ID_FULL ).isEqual( new Field( PlanoRiscosData.AREA_ID_FULL ) ), + new Field( PlanoRiscosData.ID_FULL ).isEqual( new Field( PlanoMedidasData.RISCO_ID_FULL ) ), + new Field( EstadoMedidasData.ID_FULL ).isEqual( new Field( PlanoMedidasData.ESTADO_MEDIDAS_ID_FULL ) ), + new Field( PlanoValoresQualitativosData.ID_FULL ).isEqual( new Field( PlanoRiscosData.VALOR_QUALITATIVO_ID_FULL ) ), + }, + new String[]{ "COALESCE( " + EstadoMedidasData.DESCRICAO_FULL + ", 'n.d.' )", + "COALESCE( ''|| " + PlanoRiscosData.VALOR_FULL + "," + PlanoValoresQualitativosData.DESCRICAO_FULL + " )", + "COUNT( * )", + EstadoMedidasData.ORDEM_FULL, + PlanoRiscosData.VALOR_FULL }, + expr, + new String[]{ "4", "5", "2" }, + new String[]{ "1", "4", "2", "5" }, + null, + null ) ; + select.disableOrderFieldsVerification(); + Virtual2DArray array = getExecuter().executeQuery( select ); + List linhas = new ArrayList(); + int total = 0; + String last = null; + int totalEstado = 0; + for( int n = 0; n < array.columnLength(); n++ ) + { + String estado = array.get( n, 0 ); + if( last == null ? estado != null : !last.equals( estado ) ) + { + if( totalEstado > 0 ) + { + linhas.add( new LinhaEstatistica( "", "TOTAL", 0, totalEstado ) ); + } + last = estado; + totalEstado = 0; + } + else + { + estado = ""; + } + String valoracao = array.get( n, 1 ); + Integer count = ( ( Number ) array.get( n, 2 ) ).intValue(); + total += count; + totalEstado += count; + linhas.add( new LinhaEstatistica( estado, valoracao, 0, count) ); + } + linhas.add( new LinhaEstatistica( "", "TOTAL", 0, totalEstado ) ); + for( LinhaEstatistica linha : linhas ) + { + linha.setPercentagem( ( int ) Math.round( linha.getQuantidade().doubleValue() * 100.0 / (double) total ) ); + } + linhas.add( new LinhaEstatistica( "TOTAL", "", 100, total ) ); + return linhas; + } + +// public List getEstabelecimentosForEstatistica( Utilizador u ) + public List getEstabelecimentosForEstatistica( Utilizador u ) + throws Exception + { + Expression exp = new Field( db.data.siprp_local.outer.EstabelecimentosData.EMPRESA_ID_FULL ).isEqual( 32 ).and( + new Field( db.data.siprp_local.outer.EstabelecimentosData.INACTIVO_FULL ).isDifferent( "y" ) ); + int userType = u.getTipo().intValue(); + if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS + && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH + && userType != Global.GESTOR ) + { + exp = exp.and( new Field( db.data.siprp_local.outer.EstabelecimentosData.ID_FULL ).isEqual( u.getEstabelecimento_id() ) ); + } + Select select = + new Select2( new String[]{ db.data.siprp_local.outer.EstabelecimentosData.TABLENAME }, + new Integer[]{}, + new Expression[]{}, + new String[]{ db.data.siprp_local.outer.EstabelecimentosData.ID_FULL, db.data.siprp_local.outer.EstabelecimentosData.NOME_FULL }, + exp, + new String[]{ db.data.siprp_local.outer.EstabelecimentosData.NOME_FULL }, + null, + null, + null); + Virtual2DArray array = getLocalExecuter().executeQuery( select ); + List estabelecimentos = new ArrayList(); + for( int n = 0; n < array.columnLength(); n++ ) + { + estabelecimentos.add( new MappableObject( ( Integer ) array.get( n, 0), ( String ) array.get( n, 1 ) ) ); + } + return estabelecimentos; +// int userType = u.getTipo().intValue(); +// if ( userType != Global.DIRECTOR_SIPRP && userType != Global.TECNICO_HS +// && userType != Global.DIRECTOR_NACIONAL_SEGURANCA && userType != Global.DIRECTOR_GERAL_RH +// && userType != Global.GESTOR ) +// { +// return getProvider().listLoad( EstabelecimentosData.class, new Object[]{ u.getEstabelecimento_id() }, +// new String[]{ EstabelecimentosData.ID_FULL }, new String[]{ EstabelecimentosData.NOME_FULL } ); +// } +// else +// { +// return getProvider().listLoad( EstabelecimentosData.class, EstabelecimentosData.NOME_FULL); +// } + } +} diff --git a/trunk/PlanosActuacao/src/db/providers/RelatoriosDataProvider.java b/trunk/PlanosActuacao/src/db/providers/RelatoriosDataProvider.java new file mode 100644 index 00000000..68af45e1 --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/RelatoriosDataProvider.java @@ -0,0 +1,488 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.utils.error.ErrorLogger; +import db.data.siprp_local.outer.EmpresasData; +import db.data.siprp_local.outer.ImageData; +import db.entidades.Area; +import db.entidades.Medida; +import db.entidades.PlanoActuacao; +import db.entidades.PostoTrabalho; +import db.entidades.Risco; +import db.entidades.Valor; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.LinkedList; +import java.util.List; +import utils.Utils; + +/** + * + * @author lluis + */ +public class RelatoriosDataProvider extends GenericDataProvider +{ +// private DbLocal dblocal = DbLocal.getInstance(); + + private static RelatoriosDataProvider INSTANCE = null; + + private RelatoriosDataProvider() throws Exception + { + super(); +// dblocal.connect(); + } + + public static synchronized RelatoriosDataProvider getInstance() throws Exception + { + if ( INSTANCE == null ) + { + INSTANCE = new RelatoriosDataProvider(); + } + return INSTANCE; + } + + + public PlanoActuacao getFullPlano(PlanoActuacao plano, Integer relatorioId) + { + try + { + plano = getAreasByPlano(plano, relatorioId); + } + catch(Exception ex) + { + ErrorLogger.logException( ex ); + } + + return plano; + } + + private PlanoActuacao getAreasByPlano( PlanoActuacao plano, Integer relatorioID ) throws Exception + { + Statement st = createLocalStatement(); + + String sql = "select distinct area_id, hs_relatorio_area.description as descricao from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where hs_relatorio.id = " + relatorioID + " "; + sql += "order by area_id "; + System.out.println("AREAS BY PLANO SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + + List< Area > areas = new LinkedList< Area >(); + if ( rs.isBeforeFirst() ) + { + rs.first(); + do + { + Area a = new Area(); + a.setId(new Integer( rs.getInt("area_id") )); + a.setArea_id(a.getId()); + if(existemMedidasByArea(a.getId())) + { + a.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); + try + { + a.setRiscos(getRiscosByArea(a)); + } + catch(Exception ex) + { + System.out.println("ERRO RISCOS BY AREA !!!!"); + ErrorLogger.logException( ex ); + a.setRiscos(null); + } + + areas.add(a); + } + + }while(rs.next()); + plano.setAreas(areas); + } + return plano; + } + + private List getRiscosByArea(Area a) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select distinct hs_relatorio_risco.id, hs_relatorio_risco.description as descricao from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where area_id = " + a.getId() + " "; + sql += "order by hs_relatorio_risco.id "; + System.out.println("RISCOS BY AREA SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + List< Risco > riscos = new LinkedList< Risco >(); + if(rs.isBeforeFirst()) + { + + rs.first(); + do + { + Risco r = new Risco(); + r.setId(new Integer( rs.getInt("id") )); + if(existemMedidasByRisco(r.getId())) + { + r.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); + r.setValores(getValoresByRisco(r, a)); + //Integer valor = getValorByRisco(r, a); + //r.setValorQuantitativo(valor); + r.setRisco_id(new Integer( rs.getInt("id") )); + r.setMedidas(getMedidasByRisco( r, a)); + riscos.add(r); + } + + }while(rs.next()); + } + return riscos; + + } + + private List getValoresByRisco(Risco r, Area a) throws Exception + //private Integer getValorByRisco(Risco r, Area a) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select valor from "; + sql += "(select distinct hs_relatorio_posto_risco.risco_id, "; + sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; + sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade "; + sql += "else hs_relatorio_posto_risco.valor_qualitativo_id "; + sql += "end as valor "; + sql += "from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio_posto_risco on (hs_relatorio_posto_risco.posto_id = hs_relatorio_posto.id and hs_relatorio_posto_risco.risco_id = hs_relatorio_risco.id) "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where hs_relatorio_posto_risco.risco_id = " + r.getId() + " and area_id = " + a.getId() + ") subquery "; + sql += "order by subquery.valor"; + System.out.println("VALORES BY RISCO : " + sql); + ResultSet rs = st.executeQuery(sql); + List< Valor > valores = new LinkedList< Valor >(); + Integer valor = null; + if(rs.isBeforeFirst()) + { + rs.first(); + do + { + Valor v = new Valor(); + Object oValor = rs.getObject("valor"); + + if(oValor == null) + { + v.setValorQuantitativo(null); + //r.setValorQuantitativo(null); + valor = null; + } + else + { + v.setValorQuantitativo((Integer) oValor); + //r.setValorQuantitativo((Integer) oValor); + valor = (Integer) oValor; + } +// System.out.println("RISCO : " + r.getId().toString() + "VALOR : " + oValor.toString()); + //int valor = rs.getInt("valor"); + //v.setValorQuantitativo(new Integer(valor)); + //v.setMedidas(getMedidasByValor(v, r, a)); + valores.add(v); + }while(rs.next()); + } + return valores; + //return valor; + } + +// private List getMedidasByValor(Valor v, Risco r, Area a) throws Exception +// { +// Statement st = dblocal.createStatement(); +// String sql = "select distinct medida_id, valor, descricao from "; +// sql += "( select distinct hs_relatorio_posto_medida.medida_id, hs_relatorio_posto_risco.risco_id, hs_relatorio_medida.description as descricao, "; +// sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; +// sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade "; +// sql += "else hs_relatorio_posto_risco.valor_qualitativo_id "; +// sql += "end as valor "; +// sql += "from hs_relatorio_posto "; +// sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; +// sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; +// sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; +// sql += "inner join hs_relatorio_posto_risco on (hs_relatorio_posto_risco.posto_id = hs_relatorio_posto.id and hs_relatorio_posto_risco.risco_id = hs_relatorio_risco.id) "; +// sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; +// sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; +// sql += "where hs_relatorio_posto_risco.risco_id = " + r.getId() + " and area_id = " + a.getId() + " and hs_relatorio_posto_medida.is_plano_actuacao = true" + ") subquery "; +// //sql += "where hs_relatorio_posto_risco.risco_id = " + r.getId() + " and area_id = " + a.getId() + ") subquery "; +// //sql += "where valor = " + v.getValorQuantitativo() + " "; +// sql += "order by subquery.medida_id, valor"; +// System.out.println("MEDIDAS BY VALOR SQL : " + sql); +// ResultSet rs = st.executeQuery(sql); +// List medidas = new ArrayList(); +// if(rs.isBeforeFirst()) +// { +// rs.first(); +// do +// { +// Medida m = new Medida(); +// //int valor = rs.getInt("valor"); +// //m.setValorQuantitativo(new Integer(valor)); +// m.setId(new Integer( rs.getInt("medida_id") )); +// m.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); +// m.setPostos(getPostosByMedidaAndValor(m, v, a)); +// medidas.add(m); +// }while(rs.next()); +// } +// return medidas; +// } + + private List getMedidasByRisco(Risco r, Area a) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select distinct medida_id, valor, descricao from "; + sql += "( select distinct hs_relatorio_posto_medida.medida_id, hs_relatorio_posto_risco.risco_id, hs_relatorio_medida.description as descricao, "; + sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; + sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade "; + sql += "else hs_relatorio_posto_risco.valor_qualitativo_id "; + sql += "end as valor "; + sql += "from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio_posto_risco on (hs_relatorio_posto_risco.posto_id = hs_relatorio_posto.id and hs_relatorio_posto_risco.risco_id = hs_relatorio_risco.id) "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where hs_relatorio_posto_risco.risco_id = " + r.getId() + " and area_id = " + a.getId() + " and hs_relatorio_posto_medida.is_plano_actuacao = true" + ") subquery "; + //sql += "where hs_relatorio_posto_risco.risco_id = " + r.getId() + " and area_id = " + a.getId() + ") subquery "; + //sql += "where valor = " + v.getValorQuantitativo() + " "; + sql += "order by subquery.medida_id, valor"; + System.out.println("MEDIDAS BY RISCO SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + List< Medida > medidas = new LinkedList< Medida >(); + if ( rs.isBeforeFirst() ) + { + rs.first(); + do + { + Medida m = new Medida(); + //int valor = rs.getInt("valor"); + //m.setValorQuantitativo(new Integer(valor)); + m.setId(new Integer( rs.getInt("medida_id") )); + m.setMedida_id(m.getId()); + m.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); + //m.setPostos(getPostosByMedidaAndValor(m, v, a)); + m.setPostos(getPostosByMedida(r, m, a)); + medidas.add(m); + }while(rs.next()); + } + return medidas; + } + +// private List getPostosByMedidaAndValor(Medida m, Valor v, Area a) throws Exception +// { +// Statement st = dblocal.createStatement(); +// String sql = "select subquery.posto_id, valor, descricao from "; +// sql += "(select hs_relatorio_posto_medida.posto_id, hs_relatorio_posto.description as descricao, "; +// sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; +// sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade "; +// sql += "else hs_relatorio_posto_risco.valor_qualitativo_id "; +// sql += "end as valor "; +// sql += "from hs_relatorio_posto_medida "; +// sql += "inner join hs_relatorio_posto_risco on hs_relatorio_posto_risco.posto_id = hs_relatorio_posto_medida.posto_id "; +// sql += "inner join hs_relatorio_posto on hs_relatorio_posto.id = hs_relatorio_posto_medida.posto_id "; +// sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; +// sql += "where medida_id = " + m.getId() + " and area_id = " + a.getId() + ") subquery "; +// //sql += "where valor = " + v.getValorQuantitativo(); +// System.out.println("POSTOS BY MEDIDA SQL : " + sql); +// ResultSet rs = st.executeQuery(sql); +// List postos = new ArrayList(); +// if(rs.isBeforeFirst()) +// { +// rs.first(); +// do +// { +// PostoTrabalho p = new PostoTrabalho(); +// p.setId(new Integer( rs.getInt("posto_id") )); +// p.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); +// postos.add(p); +// }while(rs.next()); +// } +// return postos; +// } + + private List getPostosByMedida(Risco r, Medida m, Area a) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select subquery.posto_id, valor, descricao from "; + sql += "(select hs_relatorio_posto_medida.posto_id, hs_relatorio_posto.description as descricao, "; + sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; + sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade "; + sql += "else hs_relatorio_posto_risco.valor_qualitativo_id "; + sql += "end as valor "; + sql += "from hs_relatorio_posto_medida "; + sql += "inner join hs_relatorio_posto_risco on hs_relatorio_posto_risco.posto_id = hs_relatorio_posto_medida.posto_id "; + sql += "inner join hs_relatorio_posto on hs_relatorio_posto.id = hs_relatorio_posto_medida.posto_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where medida_id = " + m.getId() + " and area_id = " + a.getId() + " and risco_id = " + r.getId() + ") subquery "; + //sql += "where valor = " + v.getValorQuantitativo(); + System.out.println("POSTOS BY MEDIDA SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + List< PostoTrabalho > postos = new LinkedList< PostoTrabalho >(); + if(rs.isBeforeFirst()) + { + rs.first(); + do + { + PostoTrabalho p = new PostoTrabalho(); + p.setId(new Integer( rs.getInt("posto_id") )); + p.setPosto_id(p.getId()); + p.setDescricao(Utils.unicodeToHTML(rs.getString("descricao"))); + postos.add(p); + }while(rs.next()); + } + return postos; + } + + + + private boolean existemMedidasByArea(Integer area_id) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select distinct medida_id, valor, descricao "; + sql += "from ( select distinct hs_relatorio_posto_medida.medida_id, hs_relatorio_posto_risco.risco_id, hs_relatorio_medida.description as descricao, "; + sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; + sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade else hs_relatorio_posto_risco.valor_qualitativo_id end as valor from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio_posto_risco on (hs_relatorio_posto_risco.posto_id = hs_relatorio_posto.id and hs_relatorio_posto_risco.risco_id = hs_relatorio_risco.id) "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where area_id = " + area_id + " and hs_relatorio_posto_medida.is_plano_actuacao = true) subquery order by subquery.medida_id, valor"; + System.out.println("EXISTEM MEDIDAS BY AREA SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + if(rs.isBeforeFirst()) + { + return true; + } + else + { + return false; + } + } + + private boolean existemMedidasByRisco(Integer risco_id) throws Exception + { +// Statement st = dblocal.createStatement(); + Statement st = createLocalStatement(); + + String sql = "select distinct medida_id "; + sql += "from ( select distinct hs_relatorio_posto_medida.medida_id, hs_relatorio_posto_risco.risco_id, hs_relatorio_medida.description as descricao, "; + sql += "case when hs_relatorio_posto_risco.valor_qualitativo_id isnull and hs_relatorio_posto_risco.probabilidade isnull and hs_relatorio_posto_risco.severidade isnull then null "; + sql += "when hs_relatorio_posto_risco.valor_qualitativo_id isnull then hs_relatorio_posto_risco.probabilidade * hs_relatorio_posto_risco.severidade else hs_relatorio_posto_risco.valor_qualitativo_id end as valor from hs_relatorio_posto "; + sql += "inner join hs_relatorio_posto_medida on hs_relatorio_posto_medida.posto_id = hs_relatorio_posto.id "; + sql += "inner join hs_relatorio_medida on hs_relatorio_medida.id = hs_relatorio_posto_medida.medida_id "; + sql += "inner join hs_relatorio_risco on hs_relatorio_risco.id = hs_relatorio_medida.risco_id "; + sql += "inner join hs_relatorio_posto_risco on (hs_relatorio_posto_risco.posto_id = hs_relatorio_posto.id and hs_relatorio_posto_risco.risco_id = hs_relatorio_risco.id) "; + sql += "inner join hs_relatorio on hs_relatorio.id = hs_relatorio_risco.relatorio_id "; + sql += "inner join hs_relatorio_area on hs_relatorio_area.id = area_id "; + sql += "where hs_relatorio_posto_risco.risco_id = " + risco_id + " and hs_relatorio_posto_medida.is_plano_actuacao = true) subquery order by medida_id"; + System.out.println("EXISTEM MEDIDAS BY RISCO SQL : " + sql); + ResultSet rs = st.executeQuery(sql); + if(rs.isBeforeFirst()) + { + return true; + } + else + { + return false; + } + + } + + + public String getEmpresaNome(Integer empresa_id) throws Exception + { + String nome = ""; + EmpresasData empresaData = getLocalProvider().load( EmpresasData.class, empresa_id, EmpresasData.ID ); + if ( empresaData != null ) + { + nome = Utils.unicodeToHTML( empresaData.getDesignacao_social() ); + } + return nome; + +// Statement st = createLocalStatement(); +// +// String sql ="SELECT designacao_social FROM empresas WHERE id = " + empresa_id; +// ResultSet rslocal = st.executeQuery(sql); +// rslocal.first(); +// String nome = Utils.unicodeToHTML(rslocal.getString("designacao_social")); +// return nome; + } + + public byte[] getLogoByEmpresa( Integer empresaId ) + throws Exception + { + byte[] logo = null; + EmpresasData empresaData = getLocalProvider().load( EmpresasData.class, empresaId, EmpresasData.ID ); + if ( empresaData != null ) + { + Integer logoID = empresaData.getEmpresa_logo_id(); + logo = getLogo( logoID ); + } + return logo; + +// Statement st = createLocalStatement(); +// +// String sql = "select empresa_logo_id from empresas where id = " + empresaId; +// ResultSet rslocal = st.executeQuery(sql); +// if ( rslocal.isBeforeFirst() ) +// { +// rslocal.first(); +// Integer logoId = new Integer( rslocal.getInt("empresa_logo_id") ); +// byte[] logo = getLogo( logoId ); +// return logo; +// } +// +// return null; + } + + + public byte[] getLogo( Integer logoID ) throws Exception + { + byte[] logo = null; + ImageData imageData = getLocalProvider().load( ImageData.class, logoID, ImageData.ID ); + if ( imageData != null ) + { + logo = imageData.getImage_data(); + } + System.out.println( "\nRelatoriosDataProvider . getLogo( " + logoID + " ) : " + ( logo == null ? "null" : "size = " + logo.length ) ); + return logo; + } + +// public byte[] getLogo(Integer logoId) throws Exception +// { +// Statement st = createLocalStatement(); +// +// String sql = "select image_data from image where id = " + logoId; +// ResultSet rslocal = st.executeQuery(sql); +// rslocal.first(); +// byte[] logo = rslocal.getBytes("image_data"); +// System.out.println("LOGO SIZE : " + logo.length); +// return logo; +// } +} \ No newline at end of file diff --git a/trunk/PlanosActuacao/src/db/providers/RiscoLogic.java b/trunk/PlanosActuacao/src/db/providers/RiscoLogic.java new file mode 100644 index 00000000..bf86295d --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/RiscoLogic.java @@ -0,0 +1,171 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.utils.error.ErrorLogger; +import db.data.siprp.outer.PlanoValoresQualitativosData; +import db.entidades.Medida; +import db.entidades.Risco; +import db.entidades.Utilizador; +import utils.Global; +import java.util.Date; +import java.util.List; + +/** + * + * @author dneves + */ +public class RiscoLogic +{ + + private static RiscoLogic INSTANCE = null; + + private RiscoLogic() + { + + } + + public static synchronized RiscoLogic getInstance() + { + if ( INSTANCE == null ) + { + INSTANCE = new RiscoLogic(); + } + return INSTANCE; + } + + + private boolean hasValue( Object obj ) + { + boolean result = false; + if ( obj != null ) + { + if ( obj instanceof String ) + { + result = ! "".equals( ( ( String ) obj ).trim() ); + } + else if ( obj instanceof Date ) + { + result = true; + } + } + return result; + } + + private boolean isRiscoTratado( Risco r ) + { + boolean result = false; + + String responsavelExecucao = r.getResponsavel_execucao(); + String por = r.getPor(); + String recursosNecessarios = r.getRecursos_necessarios(); + Date dataInicio = r.getData_inicio(); + Date dataFim = r.getData_fim(); + + result = hasValue( responsavelExecucao ) && hasValue( por ) && hasValue( recursosNecessarios ) + && hasValue( dataInicio ) && hasValue( dataFim ); + return result; + } + + + public boolean isRiscoTratado( Risco risco, Utilizador user, boolean forceCheck ) + { + boolean isTratado = false; + + if ( risco != null && user == null ) + { + isTratado = isRiscoTratado( risco ); + } + else if ( risco != null && user != null ) + { + int userType = user.getTipo() == null ? -1 : user.getTipo().intValue(); + switch ( userType ) + { + case Global.RESPONSAVEL_SEGURANCA : + { + String resp = risco.getResponsavel_execucao(); + String por = risco.getPor(); + String rec = risco.getRecursos_necessarios(); + Date dataInicio = risco.getData_inicio(); + Date dataFim = risco.getData_fim(); + + isTratado = hasValue( resp ) && hasValue( por ) && hasValue( rec ) && hasValue( dataInicio ) && hasValue( dataFim ); + break; + } + case Global.DIRECTOR_LOJA : + { + String parecer = risco.getParecer_dl(); + + isTratado = forceCheck ? hasValue( parecer ) : true; + + break; + } + case Global.DIRECTOR_NACIONAL_SEGURANCA : + { + String parecer = risco.getParecer_dns(); + + isTratado = forceCheck ? hasValue( parecer ) : true; + + break; + } + case Global.TECNICO_HS : + { + isTratado = true; + + if ( forceCheck ) + { + String verify = risco.getVerificacao_siprp(); + isTratado = hasValue( verify ); + List< Medida > medidas = risco.getMedidas(); + for ( int i = 0; i < medidas.size() && isTratado; i++ ) + { + Medida m = medidas.get( i ); + Integer estadoMedida = m.getValidarMedidaId(); + isTratado &= estadoMedida != null; + } + } + + break; + } + } + } + return isTratado; + } + + + public String getValor( Risco r ) + { + String result = null; + if ( r.getValorQuantitativo() != null ) + { + result = r.getValorQuantitativo().toString(); + } + else if ( r.getValorQualitativoID() != null ) + { + result = getValorQualitativoByID( r.getValorQualitativoID() ); + } + return result == null ? Global.VALOR_INDETERMINADO : result; + } + + private String getValorQualitativoByID( Integer id ) + { + String result = null; + try + { + PlanoValoresQualitativosData valor = PlanosDataProvider.getInstance().loadValorQualitativoByID( id ); + if ( valor != null ) + { + result = valor.getDescricao(); + } + } + catch ( Exception e ) + { + ErrorLogger.logException( e ); + } + return result; + } + +} diff --git a/trunk/PlanosActuacao/src/db/providers/UtilizadoresDataProvider.java b/trunk/PlanosActuacao/src/db/providers/UtilizadoresDataProvider.java new file mode 100644 index 00000000..be190c5e --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/UtilizadoresDataProvider.java @@ -0,0 +1,262 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.utils.arrays.Virtual2DArray; +import com.evolute.utils.sql.Expression; +import com.evolute.utils.sql.Field; +import com.evolute.utils.sql.Select2; +import db.data.siprp.outer.UtilizadoresData; +import db.entidades.Utilizador; +import utils.Global; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.LinkedList; +import java.util.List; + +/** + * + * @author lluis + */ +public class UtilizadoresDataProvider extends GenericDataProvider +{ + private static UtilizadoresDataProvider INSTANCE = null; + + private UtilizadoresDataProvider() throws Exception + { + super(); + + } + + public static synchronized UtilizadoresDataProvider getInstance() throws Exception + { + if ( INSTANCE == null ) + { + INSTANCE = new UtilizadoresDataProvider(); + } + return INSTANCE; + } + + + public Utilizador getUtilizador( String login ) throws Exception + { + Utilizador user = null; + + Select2 query = new Select2( + new String[] { "utilizadores" }, + new Integer[] {}, + new Expression[] {}, + new String[] { "utilizadores.id" }, + new Field( "utilizadores.apagado" ).isEqual( "n" ).and( + new Field( "LOWER( utilizadores.login )" ).isEqual( login.toLowerCase() ) + ), + new String[] {}, + null, null, null + ); + Virtual2DArray result = getExecuter().executeQuery( query ); + if ( result != null && result.columnLength() > 0 ) + { + Integer userID = result.get( 0, 0 ); + user = getUtilizador( userID ); + } + return user; + } + + public Utilizador getUtilizador( Integer userID ) throws Exception + { + Utilizador user = null; + UtilizadoresData userData = getProvider().load( UtilizadoresData.class, userID ); + user = copyFrom( userData ); + return user; + } + + private Utilizador copyFrom( UtilizadoresData userData ) + { + Utilizador user = null; + if ( userData != null ) + { + user = new Utilizador(); + user.setId( userData.getId() ); + user.setLogin( userData.getLogin() ); + user.setPassword( userData.getPassword() ); + user.setData_password( userData.getData_password() ); + user.setEmail( userData.getEmail() ); + user.setEmpresa_id( userData.getEmpresa_id() ); + user.setEstabelecimento_id( userData.getEstabelecimento_id() ); + user.setAdministrador( userData.getAdministrador() ); + user.setTipo( userData.getTipo() ); + user.setNumero_cedula( userData.getNumero_cedula() ); + user.setCap( userData.getCap() ); + user.setNome( userData.getNome() ); + user.setMedico_id( userData.getMedico_id() ); + user.setFuncionario_hst_id( userData.getFuncionario_hst_id() ); + user.setActivo( userData.getActivo() ); + user.setResponsavel_loja( userData.getResponsavel_loja() ); + user.setGestor_geral( userData.getGestor_geral() ); + user.setApagado( userData.getApagado() ); + } + return user; + } + +// public Utilizador getUtilizador( Integer id ) throws Exception +// { +// Utilizador u = null; +// Statement st = createStatement(); +// String sql = "SELECT * FROM utilizadores WHERE id = " + id; +// ResultSet rs = st.executeQuery( sql ); +// if ( rs.first() ) +// { +// u = new Utilizador(); +// u.setId(new Integer(rs.getInt("id"))); +// u.setLogin(rs.getString("login")); +// u.setPassword(rs.getString("password")); +// u.setData_password(rs.getDate("data_password")); +// u.setEmail(rs.getString("email")); +// u.setEmpresa_id(new Integer(rs.getInt("empresa_id"))); +// u.setEstabelecimento_id(new Integer(rs.getInt("estabelecimento_id"))); +// u.setAdministrador(rs.getString("administrador")); +// u.setTipo(new Integer(rs.getInt("tipo"))); +// u.setNumero_cedula(rs.getString("numero_cedula")); +// u.setCap(rs.getString("cap")); +// u.setNome(rs.getString("nome")); +// u.setMedico_id(new Integer(rs.getInt("medico_id"))); +// u.setFuncionario_hst_id(new Integer(rs.getInt("funcionario_hst_id"))); +// u.setActivo(rs.getString("activo")); +// u.setResponsavel_loja(rs.getString("responsavel_loja")); +// u.setGestor_geral(rs.getString("gestor_geral")); +// u.setApagado(rs.getString("apagado")); +// } +// return u; +// } + + public List< Utilizador > getUtilizadoresListByTipo( Integer tipo, String responsavel_loja, Integer estabelecimento_id ) + throws Exception + { + List< Utilizador > list = new LinkedList< Utilizador >(); + int type = tipo.intValue(); + + Expression where = new Field( UtilizadoresData.ACTIVO_FULL ).isEqual( "y" ); + where = where.and( new Field( UtilizadoresData.APAGADO_FULL ).isEqual( "n" ) ); + where = where.and( new Field( UtilizadoresData.TIPO_FULL ).isEqual( type ) ); + if ( type == Global.RESPONSAVEL_SEGURANCA || type == Global.DIRECTOR_LOJA ) + { + where = where.and( new Field( UtilizadoresData.ESTABELECIMENTO_ID_FULL ).isEqual( estabelecimento_id ) ); + } + if ( type == Global.RESPONSAVEL_SEGURANCA && "y".equals( responsavel_loja ) ) + { + where = where.and( new Field( UtilizadoresData.RESPONSAVEL_LOJA_FULL ).isEqual( "y" ) ); + } + + if ( type == Global.DIRECTOR_LOJA || type == Global.TECNICO_HS || type == Global.DIRECTOR_NACIONAL_SEGURANCA + || ( type == Global.RESPONSAVEL_SEGURANCA && "y".equals( responsavel_loja ) ) ) + { + System.out.println( "\nUtilizadoresDataProvider . getUtilizadoresListByTipo( " + tipo + ", " + responsavel_loja + ", " + estabelecimento_id + " ) : " ); + System.out.println( "\tSQL : SELECT * FROM utilizadores WHERE " + where.toString() ); + + List< UtilizadoresData > listData = getProvider().listLoad( + UtilizadoresData.class, where, new String[] { UtilizadoresData.NOME }, null ); + for ( UtilizadoresData userData : listData ) + { + list.add( copyFrom( userData ) ); + } + } + + +// String sql = ""; +// String estabelecimento_constraint = ""; +// if ( type == Global.DIRECTOR_LOJA || type == Global.RESPONSAVEL_SEGURANCA || type == Global.DIRECTOR_NACIONAL_SEGURANCA ) +// { +// estabelecimento_constraint = " AND estabelecimento_id = " + estabelecimento_id; +// } +// if ( type == Global.RESPONSAVEL_SEGURANCA && responsavel_loja.matches( "y" ) ) +// { +// sql = "SELECT * FROM utilizadores WHERE activo = 'y' AND apagado = 'n' AND tipo = " + tipo + estabelecimento_constraint + " AND responsavel_loja = 'y'"; +// } +// else if ( type == Global.DIRECTOR_LOJA || type == Global.TECNICO_HS || type == Global.DIRECTOR_NACIONAL_SEGURANCA ) +// { +// sql = "SELECT * FROM utilizadores WHERE activo = 'y' AND apagado = 'n' AND tipo = " + tipo + estabelecimento_constraint; +// } +// +// System.out.println( "UTILIZADORES LIST BY TIPO SQL : " + sql ); +// Statement st = createStatement(); +// ResultSet rs = st.executeQuery( sql ); +// if ( rs.isBeforeFirst() ) +// { +// rs.first(); +// do +// { +// Utilizador u = new Utilizador(); +// u.setId( new Integer( rs.getInt( "id" ) ) ); +// u.setLogin( rs.getString( "login" ) ); +// u.setPassword( rs.getString( "password" ) ); +// u.setData_password( rs.getDate( "data_password" ) ); +// u.setEmail( rs.getString( "email" ) ); +// u.setEmpresa_id( new Integer( rs.getInt( "empresa_id" ) ) ); +// u.setEstabelecimento_id( new Integer( rs.getInt( "estabelecimento_id" ) ) ); +// u.setAdministrador( rs.getString( "administrador" ) ); +// u.setTipo( new Integer( rs.getInt( "tipo" ) ) ); +// u.setNumero_cedula( rs.getString( "numero_cedula" ) ); +// u.setCap( rs.getString( "cap" ) ); +// u.setNome( rs.getString( "nome" ) ); +// u.setMedico_id( new Integer( rs.getInt( "medico_id" ) ) ); +// u.setFuncionario_hst_id( new Integer( rs.getInt( "funcionario_hst_id" ) ) ); +// u.setActivo( rs.getString( "activo" ) ); +// u.setResponsavel_loja( rs.getString( "responsavel_loja" ) ); +// list.add( u ); +// } +// while ( rs.next() ); +// } + + return list; + } + + public List< Utilizador > getUtilizadoresList() throws Exception + { + List< Utilizador > list = new LinkedList< Utilizador >(); + + Expression where = new Field( UtilizadoresData.ACTIVO_FULL ).isEqual( "y" ).and( + new Field( UtilizadoresData.APAGADO_FULL ).isEqual( "n" ) ); + + List< UtilizadoresData > listData = getProvider().listLoad( UtilizadoresData.class, where, new String[] { UtilizadoresData.NOME }, null ); + for ( UtilizadoresData userData : listData ) + { + list.add( copyFrom( userData ) ); + } + return list; + } + +// public ArrayList getUtilizadoresList() throws Exception +// { +// ArrayList list = new ArrayList(); +// Statement st = createStatement(); +// String sql = "select * from utilizadores where activo = 'y' and apagado = 'n'"; +// +// ResultSet rs = st.executeQuery(sql); +// rs.first(); +// do +// { +// Utilizador u = new Utilizador(); +// u.setId(new Integer(rs.getInt("id"))); +// u.setLogin(rs.getString("login")); +// u.setPassword(rs.getString("password")); +// u.setData_password(rs.getDate("data_password")); +// u.setEmail(rs.getString("email")); +// u.setEmpresa_id(new Integer(rs.getInt("empresa_id"))); +// u.setEstabelecimento_id(new Integer(rs.getInt("estabelecimento_id"))); +// u.setAdministrador(rs.getString("administrador")); +// u.setTipo(new Integer(rs.getInt("tipo"))); +// u.setNumero_cedula(rs.getString("numero_cedula")); +// u.setCap(rs.getString("cap")); +// u.setNome(rs.getString("nome")); +// u.setMedico_id(new Integer(rs.getInt("medico_id"))); +// u.setFuncionario_hst_id(new Integer(rs.getInt("funcionario_hst_id"))); +// u.setActivo(rs.getString("activo")); +// u.setResponsavel_loja(rs.getString("responsavel_loja")); +// list.add(u); +// }while(rs.next()); +// return list; +// } +} diff --git a/trunk/PlanosActuacao/src/db/providers/UtilizadoresLogic.java b/trunk/PlanosActuacao/src/db/providers/UtilizadoresLogic.java new file mode 100644 index 00000000..97bd2fc3 --- /dev/null +++ b/trunk/PlanosActuacao/src/db/providers/UtilizadoresLogic.java @@ -0,0 +1,47 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package db.providers; + +import com.evolute.utils.error.ErrorLogger; +import db.entidades.Utilizador; + +/** + * + * @author dneves + */ +public class UtilizadoresLogic +{ + private static UtilizadoresLogic INSTANCE = null; + + private UtilizadoresLogic() + { + + } + + public static synchronized UtilizadoresLogic getInstance() + { + if ( INSTANCE == null ) + { + INSTANCE = new UtilizadoresLogic(); + } + return INSTANCE; + } + + public String getNomeUtilizadorByID( Integer userID ) + { + String nome = ""; + try + { + Utilizador userValidacao = UtilizadoresDataProvider.getInstance().getUtilizador( userID ); + nome = userValidacao == null ? "" : userValidacao.getNome(); + } + catch ( Exception e ) + { + ErrorLogger.logException( e ); + } + return nome; + } +}