From f6498eb18725e1daa3fe4578e90fc79e28968ef6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tiago=20Sim=C3=A3o?= Date: Wed, 5 Sep 2007 10:18:06 +0000 Subject: [PATCH] git-svn-id: https://svn.coded.pt/svn/SIPRP@547 bb69d46d-e84e-40c8-a05a-06db0d633741 --- trunk/web/src/META-INF/context.xml | 2 + .../classes/siprp/pagina/GlobalConstants.java | 38 + .../classes/siprp/pagina/MailerServlet.java | 240 +++ .../classes/siprp/pagina/NewsServlet.java | 168 ++ .../classes/siprp/pagina/RecruitServlet.java | 127 ++ .../siprp/pagina/RelatorioServlet.java | 121 ++ .../classes/siprp/pagina/RequestServlet.java | 63 + .../classes/siprp/pagina/ScheduleServlet.java | 142 ++ .../siprp/pagina/doGetListaEmpresas.java | 113 ++ .../pagina/doGetListaEstabelecimentos.java | 105 ++ .../siprp/pagina/doGetListaTrabalhadores.java | 299 ++++ .../doGetListaTrabalhadoresPendentes.java | 879 ++++++++++ .../pagina/doGetListaTrabalhadoresTudo.java | 255 +++ .../siprp/pagina/doGetTrabalhador.java | 324 ++++ .../classes/siprp/pagina/doPostLogin.java | 122 ++ .../classes/siprp/pagina/siprpServlet.java | 648 ++++++++ trunk/web/src/WEB-INF/web.xml | 46 + trunk/web/src/html/clientes.html | 47 + trunk/web/src/html/colaboradores.html | 50 + trunk/web/src/html/contactos.html | 52 + .../html/conteudos/colaboradores_text.html | 111 ++ .../src/html/conteudos/contactos_text.html | 105 ++ .../html/conteudos/higiene_foto_equip_BA.html | 29 + .../web/src/html/conteudos/higiene_text.html | 59 + .../html/conteudos/higiene_text_equip.html | 36 + trunk/web/src/html/conteudos/links_text.html | 104 ++ .../web/src/html/conteudos/medicina_text.html | 32 + .../web/src/html/conteudos/politica_text.html | 69 + .../conteudos/politica_text_20050106.html | 59 + .../html/conteudos/servicos_compl_text.html | 71 + .../servicos_compl_text_20050106.html | 71 + trunk/web/src/html/conteudos/siprp_text.html | 28 + .../html/conteudos/siprp_text_inovacao.html | 22 + trunk/web/src/html/css/funcs.js | 64 + trunk/web/src/html/css/style.css | 129 ++ trunk/web/src/html/erro.html | 44 + trunk/web/src/html/frame_erro.html | 254 +++ trunk/web/src/html/higiene.html | 52 + trunk/web/src/html/index.html | 229 +++ trunk/web/src/html/links.html | 52 + trunk/web/src/html/mail/cv_enviado.html | 11 + trunk/web/src/html/mail/cv_nao_enviado.html | 12 + trunk/web/src/html/mail/envio_cv.txt | 7 + trunk/web/src/html/mail/pedido_enviado.html | 11 + trunk/web/src/html/mail/pedido_informacao.txt | 5 + .../web/src/html/mail/pedido_nao_enviado.html | 11 + trunk/web/src/html/marcacao/CalendarPopup.js | 1462 +++++++++++++++++ trunk/web/src/html/marcacao/marcacao.html | 14 + .../src/html/marcacao/marcacao_consulta.html | 49 + .../src/html/marcacao/marcacao_enviada.html | 11 + .../web/src/html/marcacao/marcacao_exame.html | 43 + .../web/src/html/marcacao/marcacao_menu.html | 62 + .../html/marcacao/marcacao_nao_enviada.html | 11 + .../marcacao/marcacao_sessao_expirou.html | 11 + trunk/web/src/html/medicina.html | 52 + .../src/html/noticias/mostrar_noticias.html | 11 + trunk/web/src/html/politica.html | 52 + trunk/web/src/html/relatorio/pedido.html | 9 + .../src/html/relatorio/pedido_enviado.html | 11 + .../html/relatorio/pedido_nao_enviado.html | 11 + .../src/html/relatorio/pedido_relatorio.html | 35 + .../html/relatorio/pedido_sessao_expirou.html | 11 + trunk/web/src/html/servicos.html | 31 + trunk/web/src/html/servicos_compl.html | 52 + trunk/web/src/html/siprp.html | 52 + trunk/web/src/html/user.html | 396 +++++ trunk/web/src/html/user_print.html | 284 ++++ trunk/web/src/missing | 4 + 68 files changed, 8192 insertions(+) create mode 100644 trunk/web/src/META-INF/context.xml create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/GlobalConstants.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/MailerServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/NewsServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/RecruitServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/RelatorioServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/RequestServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/ScheduleServlet.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEmpresas.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEstabelecimentos.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadores.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresPendentes.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresTudo.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doGetTrabalhador.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/doPostLogin.java create mode 100644 trunk/web/src/WEB-INF/classes/siprp/pagina/siprpServlet.java create mode 100644 trunk/web/src/WEB-INF/web.xml create mode 100644 trunk/web/src/html/clientes.html create mode 100644 trunk/web/src/html/colaboradores.html create mode 100644 trunk/web/src/html/contactos.html create mode 100644 trunk/web/src/html/conteudos/colaboradores_text.html create mode 100644 trunk/web/src/html/conteudos/contactos_text.html create mode 100644 trunk/web/src/html/conteudos/higiene_foto_equip_BA.html create mode 100644 trunk/web/src/html/conteudos/higiene_text.html create mode 100644 trunk/web/src/html/conteudos/higiene_text_equip.html create mode 100644 trunk/web/src/html/conteudos/links_text.html create mode 100644 trunk/web/src/html/conteudos/medicina_text.html create mode 100644 trunk/web/src/html/conteudos/politica_text.html create mode 100644 trunk/web/src/html/conteudos/politica_text_20050106.html create mode 100644 trunk/web/src/html/conteudos/servicos_compl_text.html create mode 100644 trunk/web/src/html/conteudos/servicos_compl_text_20050106.html create mode 100644 trunk/web/src/html/conteudos/siprp_text.html create mode 100644 trunk/web/src/html/conteudos/siprp_text_inovacao.html create mode 100644 trunk/web/src/html/css/funcs.js create mode 100644 trunk/web/src/html/css/style.css create mode 100644 trunk/web/src/html/erro.html create mode 100644 trunk/web/src/html/frame_erro.html create mode 100644 trunk/web/src/html/higiene.html create mode 100644 trunk/web/src/html/index.html create mode 100644 trunk/web/src/html/links.html create mode 100644 trunk/web/src/html/mail/cv_enviado.html create mode 100644 trunk/web/src/html/mail/cv_nao_enviado.html create mode 100644 trunk/web/src/html/mail/envio_cv.txt create mode 100644 trunk/web/src/html/mail/pedido_enviado.html create mode 100644 trunk/web/src/html/mail/pedido_informacao.txt create mode 100644 trunk/web/src/html/mail/pedido_nao_enviado.html create mode 100644 trunk/web/src/html/marcacao/CalendarPopup.js create mode 100644 trunk/web/src/html/marcacao/marcacao.html create mode 100644 trunk/web/src/html/marcacao/marcacao_consulta.html create mode 100644 trunk/web/src/html/marcacao/marcacao_enviada.html create mode 100644 trunk/web/src/html/marcacao/marcacao_exame.html create mode 100644 trunk/web/src/html/marcacao/marcacao_menu.html create mode 100644 trunk/web/src/html/marcacao/marcacao_nao_enviada.html create mode 100644 trunk/web/src/html/marcacao/marcacao_sessao_expirou.html create mode 100644 trunk/web/src/html/medicina.html create mode 100644 trunk/web/src/html/noticias/mostrar_noticias.html create mode 100644 trunk/web/src/html/politica.html create mode 100644 trunk/web/src/html/relatorio/pedido.html create mode 100644 trunk/web/src/html/relatorio/pedido_enviado.html create mode 100644 trunk/web/src/html/relatorio/pedido_nao_enviado.html create mode 100644 trunk/web/src/html/relatorio/pedido_relatorio.html create mode 100644 trunk/web/src/html/relatorio/pedido_sessao_expirou.html create mode 100644 trunk/web/src/html/servicos.html create mode 100644 trunk/web/src/html/servicos_compl.html create mode 100644 trunk/web/src/html/siprp.html create mode 100644 trunk/web/src/html/user.html create mode 100644 trunk/web/src/html/user_print.html create mode 100644 trunk/web/src/missing diff --git a/trunk/web/src/META-INF/context.xml b/trunk/web/src/META-INF/context.xml new file mode 100644 index 00000000..49b2eb8c --- /dev/null +++ b/trunk/web/src/META-INF/context.xml @@ -0,0 +1,2 @@ + + diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/GlobalConstants.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/GlobalConstants.java new file mode 100644 index 00000000..5f145417 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/GlobalConstants.java @@ -0,0 +1,38 @@ +/* + * GlobalConstant.java + * + * Created on 27 de Abril de 2005, 18:20 + */ + +package siprp.pagina; + +/** + * + * @author fpalma + */ +public interface GlobalConstants +{ + // BD + public static final String bdHost = "127.0.0.1"; + public static final String bdPort = "5436"; + public static final String bdUsername = "siprp"; + public static final String bdPassword = ""; + public static final String bdDriver = "org.postgresql.Driver"; + public static final String bdUrl = "jdbc:postgresql://" + bdHost + ":" + bdPort + "/siprp"; + + public static final String bdLocalHost = "127.0.0.1"; + public static final String bdLocalPort = "5436"; + public static final String bdLocalUsername = "siprp"; + public static final String bdLocalPassword = ""; + public static final String bdLocalDriver = "org.postgresql.Driver"; + public static final String bdLocalUrl = "jdbc:postgresql://" + bdHost + ":" + bdPort + "/siprp_local_3"; + + public static final String DEFAULT_EMAIL = "geral@siprp.pt"; + + public static final int TIPO_MARCACAO_EXAMES = 0; + public static final int TIPO_MARCACAO_CONSULTA = 1; + + public static final Integer ESTADO_POR_REALIZAR = new Integer( 0 ); + public static final Integer ESTADO_PARCIALMENTE_REALIZADO = new Integer( 1 ); + public static final Integer ESTADO_REALIZADO = new Integer( 2 ); +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/MailerServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/MailerServlet.java new file mode 100644 index 00000000..cbb306f1 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/MailerServlet.java @@ -0,0 +1,240 @@ +/* + * ServletAux.java + * + * Created on 10 de Março de 2005, 12:24 + */ + +package siprp.pagina; + +import javax.activation.*; +import java.io.*; +import java.util.*; + +import javax.mail.*; +import javax.mail.internet.*; +import javax.servlet.*; +import javax.servlet.http.*; +import java.sql.*; + +import org.apache.commons.mail.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +import com.evolute.utils.arrays.*; +/** + * + * @author psantos + */ +public class MailerServlet extends HttpServlet + implements GlobalConstants +{ + public static final String EMAIL = "email"; + public static final String EMAIL_MARCACAO = "email_marcacao"; + public static final String EMAIL_RECRUTAMENTO = "email_recrutamento"; + + protected static Hashtable PROPERTIES; + + public void init() + { + + try + { + String TEMPLATE_DIR = this.getServletContext().getRealPath( "/" ) + "html/"; + + Properties props = new Properties(); + props.setProperty( "file.resource.loader.path", TEMPLATE_DIR ); + Velocity.init( props ); + if( PROPERTIES == null ) + { + Class.forName(bdDriver); + Connection con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword ); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet2DArray array = new ResultSet2DArray( + stmt.executeQuery( "Select name, value FROM properties;" ) ); + PROPERTIES = new Hashtable(); + for( int n = 0; n < array.columnLength(); n++ ) + { + PROPERTIES.put( array.get( n, 0 ), array.get( n, 1 ) ); + } + con.close(); + } + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + + protected String createContent( Hashtable parameters, String[] form_fields, String template ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + for( int i = 0; i < form_fields.length; i++ ) + { + context.put( form_fields[ i ], parameters.get( form_fields[ i ] ) ); + } + + Velocity.mergeTemplate( template, Velocity.ENCODING_DEFAULT, context, output ); + + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return null; + } + + protected String showResultPage( boolean success, String success_template, String fail_template ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + String template; + if( success ) + { + template = success_template; + } + else + { + template = fail_template; + } + try + { + Velocity.mergeTemplate( template, Velocity.ENCODING_DEFAULT, context, output ); + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return null; + } + + protected boolean sendMail( String from, String destination, String subject, String content, boolean html ) + { + String smtp_server = "localhost"; + String mailer = "Evolute Mailer"; + + Properties props = System.getProperties(); + props.put( "mail.smtp.host", smtp_server ); + + String content_type = ( html ) ? "text/html" : "text/plain"; + + Session session = Session.getInstance( props, null ); + Message msg = new MimeMessage( session ); + try + { + if( from != null ) + { + msg.setFrom( new InternetAddress( from ) ); + } + msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( destination, true ) ); + msg.setSubject( subject ); + + msg.setContent( content.toString(), content_type ); + + msg.setHeader( "X-Mailer", mailer ); + msg.setSentDate( new java.util.Date() ); + Transport.send( msg ); + + return true; + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return false; + } + + protected boolean sendMail( String from, String destination, String subject, String content, boolean html, + String filename, byte attachment[], String type ) + { + String smtp_server = "localhost"; + String mailer = "Evolute Mailer"; + + Properties props = System.getProperties(); + props.put( "mail.smtp.host", smtp_server ); + + String content_type = ( html ) ? "text/html" : "text/plain"; + + Session session = Session.getInstance( props, null ); + Message msg = new MimeMessage( session ); + try + { + if( from != null ) + { + msg.setFrom( new InternetAddress( from ) ); + } + msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( destination, true ) ); + msg.setSubject( subject ); + msg.setHeader( "X-Mailer", mailer ); + msg.setSentDate( new java.util.Date() ); + + Multipart multipart = new MimeMultipart(); + BodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setContent( content.toString(), content_type ); + multipart.addBodyPart(messageBodyPart); + + messageBodyPart = new MimeBodyPart(); +// messageBodyPart.setDataHandler( +// new DataHandler( new ByteArrayDataSource( attachment, "/siprpWeb/test.txt" ))); + messageBodyPart.setContent( attachment, content_type ); + DataSource source = new ByteArrayDataSource(attachment, type); + messageBodyPart.setDataHandler( + new DataHandler(source)); + messageBodyPart.setFileName(filename); + + multipart.addBodyPart(messageBodyPart); + msg.setContent(multipart); + + Transport.send( msg ); + + return true; + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return false; + } + + private String checkParameter( String parameter ) + { + if( parameter != null && parameter.trim().length() > 0 ) + { + return parameter.trim(); + } + + return null; + } + + protected Hashtable parseParameters( Hashtable parameters ) + { + Hashtable tmp = new Hashtable(); + String[] element; + String key; + String new_element; + for( Enumeration e = parameters.keys(); e.hasMoreElements(); ) + { + key = ( String ) e.nextElement(); + element = ( String[] ) parameters.get( key ); + if( element != null ) + { + new_element = checkParameter( element[ 0 ] ); + if( new_element != null ) + { + tmp.put( key, new_element ); + } + } + } + + return tmp; + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/NewsServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/NewsServlet.java new file mode 100644 index 00000000..5122d6b2 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/NewsServlet.java @@ -0,0 +1,168 @@ +/* + * NewsServlet.java + * + * Created on 20 de Maio de 2005, 17:48 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import java.sql.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +import com.evolute.utils.*; +import com.evolute.utils.arrays.*; +import com.evolute.utils.db.*; +import com.evolute.utils.sql.*; +import com.evolute.utils.strings.*; + +/** + * + * @author lflores + */ +public class NewsServlet extends HttpServlet + implements GlobalConstants +{ + private static DBManager DBM = null; + + private static final Select SELECT = new Select( new String[]{ "not_noticias" }, + new String[]{"data", "noticia"}, new Field( "id" ).in( + new Field( "( SELECT MAX( id ) FROM not_noticias )" ) ) ); + + private SQLExecuter executer = null; + + private static boolean velocityInit = false; + + public void init() + { + if( !velocityInit ) + { + try + { + String TEMPLATE_DIR = this.getServletContext().getRealPath( "/" ) + "html/"; + + Properties props = new Properties(); + props.setProperty( "file.resource.loader.path", TEMPLATE_DIR ); + Velocity.init( props ); + } + catch( Exception ex ) + { + ex.printStackTrace(); + } + velocityInit = true; + } + + if( DBM != null ) + { + return; + } + + try + { + DBM = new JDBCManager( bdUrl + "?prepareThreshold=1", + bdUsername, bdPassword , 8, 8, 0, new SQLQuery[] {} ); + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + + private void close() + { + try + { + DBM.close(); + DBM = null; + } + catch( Exception ex ) + { + // we come here after an error + // so we discard this exception + } + } + + private String getNews() + { +//System.err.println( "NEWS: BEGIN" ); + try + { + if( executer == null ) + { + executer = ( SQLExecuter )DBM.getSharedExecuter(); + } + Virtual2DArray array = executer.executeQuery( SELECT ); + Object o[][] = array.getObjects(); + if( o != null && o.length > 0 ) + { +//System.err.println( "NEWS: " + o[ 0 ][ 0 ].toString() ); + return + //o[ 0 ][ 0 ].toString() + + StringConverter.unicodeToHTML( o[ 0 ][ 1 ].toString() ); + } + } + catch( Exception ex ) + { +//System.err.println( "NEWS: EX" ); + ex.printStackTrace(); + close(); + } +//System.err.println( "NEWS: END" ); + return null; + } + + public void doGet( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { +//System.err.println( "NEWS: GET BEGIN" ); + init(); +//System.err.println( "NEWS: AF INIT" ); + ServletOutputStream out = res.getOutputStream(); +// String queryString = req.getQueryString(); + res.setContentType( "text/html" ); + String news = getNews(); + Hashtable parameters = new Hashtable(); + if( news == null ) + { + parameters.put( "noticias", "" ); + } + else + { + parameters.put( "noticias", news ); + } +//System.err.println( "NEWS: BF SHOW" ); + out.println( showPage( "noticias/mostrar_noticias.html", parameters ) ); + } + + private String showPage( String page, Hashtable parameters ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + if( parameters != null ) + { + String key; + for( Enumeration e = parameters.keys(); e.hasMoreElements(); ) + { + key = ( String ) e.nextElement(); + context.put( key, parameters.get( key ) ); + } + } + + Velocity.mergeTemplate( page, Velocity.ENCODING_DEFAULT, context, output ); + + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + return null; + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/RecruitServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/RecruitServlet.java new file mode 100644 index 00000000..e37dfc7d --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/RecruitServlet.java @@ -0,0 +1,127 @@ +/* + * RequestServlet.java + * + * Created on 4 de Março de 2005, 18:19 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; + +import javax.servlet.*; +import javax.servlet.http.*; + +import org.apache.commons.fileupload.*; + +/** + * + * @author psantos + */ +public class RecruitServlet extends MailerServlet +{ + private final static String REC_FUNCAO = "rec_funcao"; + private final static String REC_NOME = "rec_nome"; + private final static String REC_MORADA = "rec_morada"; + private final static String REC_TELEFONE = "rec_telefone"; + private final static String REC_EMAIL = "rec_email"; + private final static String REC_CV = "rec_cv"; + + private final static String[] FORM_FIELDS = new String[]{ + REC_FUNCAO, REC_NOME, REC_MORADA, + REC_TELEFONE, REC_EMAIL, REC_CV + }; + + public void doPost( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + Hashtable parameters; + String fileName = ""; + String type = ""; + byte file[] = new byte[0]; + boolean isMultipart = FileUpload.isMultipartContent( req ); + + ServletOutputStream out = res.getOutputStream(); + res.setContentType( "text/html" ); + + if( isMultipart ) + { + parameters = new Hashtable(); + DiskFileUpload upload = new DiskFileUpload(); + upload.setSizeThreshold(1000000); + upload.setSizeMax(1000000); + List items; + try + { + items = upload.parseRequest(req); + } + catch( FileUploadException ex ) + { + out.println( showResultPage( false, "mail/pedido_enviado.html", "mail/pedido_nao_enviado.html" ) ); + return; + } + Iterator iter = items.iterator(); + while( iter.hasNext() ) + { + FileItem item = (FileItem) iter.next(); + + if (item.isFormField()) + { + String name = item.getFieldName(); + String value = item.getString(); + parameters.put( name, value ); + } + else + { + String fieldName = item.getFieldName(); + fileName = item.getName(); + file = item.get(); + if( file == null || file.length == 0 ) + { + isMultipart = false; + } + type = item.getContentType(); + } + } + } + else + { + parameters = parseParameters( new Hashtable( req.getParameterMap() ) ); + } + String content = createContent( parameters, FORM_FIELDS, "mail/envio_cv.txt" ); + + String email = DEFAULT_EMAIL; + if( PROPERTIES != null && PROPERTIES.containsKey( EMAIL_RECRUTAMENTO ) ) + { + email = ( String ) PROPERTIES.get( EMAIL_RECRUTAMENTO ); + } + String from = email; + String destination = email; + String subject = "Envio de CV através do site www.siprp.pt"; + // manda mail + boolean success; + String nome = ( String ) parameters.get( REC_NOME ); + String telefone = ( String ) parameters.get( REC_TELEFONE ); + String mail = ( String ) parameters.get( REC_EMAIL ); + if( nome == null || nome.trim().length() == 0 || telefone == null || telefone.trim().length() == 0 || + mail == null || mail.trim().length() == 0 || mail.indexOf( '@' ) == -1 ) + { +System.out.println( "nome: " + nome + " teefone: " + telefone + " email : " + email ); + success = false; + } + else if( isMultipart ) + { +System.out.println( "Multipart" ); + success = sendMail( from, destination, subject, content, false, fileName, file, type ); + } + else + { +System.out.println( "Normal" ); + success = sendMail( from, destination, subject, content, false ); + } + + // mostra pagina correspondente + + out.println( showResultPage( success, "mail/cv_enviado.html", "mail/cv_nao_enviado.html" ) ); + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/RelatorioServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/RelatorioServlet.java new file mode 100644 index 00000000..8ed2403f --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/RelatorioServlet.java @@ -0,0 +1,121 @@ +/* + * RelatorioServlet.java + * + * Created on 27 de Abril de 2005, 16:16 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; + +import javax.servlet.*; +import javax.servlet.http.*; + +import org.apache.velocity.*; +import org.apache.velocity.app.*; +/** + * + * @author fpalma + */ +public class RelatorioServlet extends MailerServlet +{ + private final static String EMPRESA = "empresa"; + private final static String EMAIL_EMPRESA = "email_empresa"; + private final static String ANO = "ano"; + + private final static String[] FORM_FIELDS = new String[]{ + EMPRESA, ANO, EMAIL_EMPRESA }; + + public void doGet( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + String queryString = req.getQueryString(); + res.setContentType( "text/html" ); + + Hashtable parameters = new Hashtable(); + + // Ir buscar os parametros à sessão + HttpSession session = req.getSession( false ); + if( session == null ) + { + // timeout + out.println( showPage( "relatorio/pedido_sessao_expirou.html", null ) ); + return; + } + + out.println( showPage( "relatorio/pedido_relatorio.html", parameters ) ); + } + + public void doPost( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + String queryString = req.getQueryString(); + res.setContentType( "text/html" ); + + // Info de marcacao + // Dados que vem no pedido: marcacao_tipo, data, hora + Hashtable parameters = parseParameters( new Hashtable( req.getParameterMap() ) ); + + // Ir buscar o resto dos parametros à sessão + HttpSession session = req.getSession( false ); + if( session == null ) + { + // timeout + out.println( showPage( "relatorio/pedido_sessao_expirou.html", null ) ); + return; + } + + parameters.put( EMPRESA, session.getAttribute( siprpServlet.sessionCompanyName ) ); + String from = ( String ) session.getAttribute( siprpServlet.sessionCompanyEmail ); + + String email = DEFAULT_EMAIL; + if( PROPERTIES != null && PROPERTIES.containsKey( EMAIL ) ) + { + email = ( String ) PROPERTIES.get( EMAIL ); + } + String destination = email; + String subject = "Pedido de envio de relatorio via web"; + if( parameters.get( ANO ) == null ) + { + parameters.put( ANO, "corrente" ); + } + String content = createContent( parameters, FORM_FIELDS, "relatorio/pedido.html" ); + // manda mail + boolean success = sendMail( from, destination, subject, content, true ); + + // mostra pagina correspondente + out.println( showResultPage( success, "relatorio/pedido_enviado.html", "relatorio/pedido_nao_enviado.html" ) ); + } + + private String showPage( String page, Hashtable parameters ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + if( parameters != null ) + { + String key; + for( Enumeration e = parameters.keys(); e.hasMoreElements(); ) + { + key = ( String ) e.nextElement(); + context.put( key, parameters.get( key ) ); + } + } + + Velocity.mergeTemplate( page, Velocity.ENCODING_DEFAULT, context, output ); + + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return null; + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/RequestServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/RequestServlet.java new file mode 100644 index 00000000..af514f89 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/RequestServlet.java @@ -0,0 +1,63 @@ +/* + * RequestServlet.java + * + * Created on 4 de Março de 2005, 18:19 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; + +import javax.servlet.*; +import javax.servlet.http.*; + +/** + * + * @author psantos + */ +public class RequestServlet extends MailerServlet +{ + private final static String REQUEST_NAME = "request_name"; + private final static String REQUEST_PHONE = "request_phone"; + private final static String REQUEST_EMAIL = "request_email"; + private final static String REQUEST_DETAILS = "request_details"; + + private final static String[] FORM_FIELDS = new String[]{ + REQUEST_NAME, REQUEST_PHONE, + REQUEST_EMAIL, REQUEST_DETAILS + }; + + public void doPost( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + res.setContentType( "text/html" ); + + /* + parametros: + request_name + request_phone + request_email + request_details + */ + // recebe info de contacto + Hashtable parameters = parseParameters( new Hashtable( req.getParameterMap() ) ); + + String content = createContent( parameters, FORM_FIELDS, "mail/pedido_informacao.txt" ); + + String from = ( String ) parameters.get( REQUEST_EMAIL ); + String email = DEFAULT_EMAIL; + if( PROPERTIES != null && PROPERTIES.containsKey( EMAIL ) ) + { + email = ( String ) PROPERTIES.get( EMAIL ); + } + String destination = email; + String subject = "Pedido de informação através do site www.siprp.pt"; + // manda mail + boolean success = sendMail( from, destination, subject, content, false ); + + // mostra pagina correspondente + out.println( showResultPage( success, "mail/pedido_enviado.html", "mail/pedido_nao_enviado.html" ) ); + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/ScheduleServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/ScheduleServlet.java new file mode 100644 index 00000000..51feffb6 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/ScheduleServlet.java @@ -0,0 +1,142 @@ +/* + * ScheduleServlet.java + * + * Created on 10 de Março de 2005, 12:22 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; + +import javax.servlet.*; +import javax.servlet.http.*; + +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +/** + * + * @author psantos + */ +public class ScheduleServlet extends MailerServlet +{ + private final static String EMPRESA = "empresa"; + private final static String ESTABELECIMENTO = "estabelecimento"; + private final static String FUNCIONARIO = "funcionario"; + private final static String MARCACAO_TIPO = "marcacao_tipo"; + private final static String DATA = "data"; + private final static String HORA = "hora"; + private final static String EMAIL_EMPRESA = "email_empresa"; + + private final static String[] FORM_FIELDS = new String[]{ + EMPRESA, ESTABELECIMENTO, FUNCIONARIO, + MARCACAO_TIPO, DATA, HORA, EMAIL_EMPRESA + }; + + public void doGet( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + String queryString = req.getQueryString(); + res.setContentType( "text/html" ); + + Hashtable parameters = new Hashtable(); + + // Ir buscar os parametros à sessão + HttpSession session = req.getSession( false ); + if( session == null ) + { + // timeout + out.println( showPage( "marcacao/marcacao_sessao_expirou.html", null ) ); + return; + } + + parameters.put( EMPRESA, session.getAttribute( siprpServlet.sessionCompanyName ) ); + parameters.put( ESTABELECIMENTO, session.getAttribute( "session_estabelecimento_nome" ) ); + parameters.put( FUNCIONARIO, session.getAttribute( "session_funcionario_nome" ) ); + + String tokens[] = queryString.split( "[?]" ); + if( tokens.length > 0 && tokens[ tokens.length - 1 ].equals( "consulta" ) ) + { + out.println( showPage( "marcacao/marcacao_consulta.html", parameters ) ); + } + else + { + out.println( showPage( "marcacao/marcacao_exame.html", parameters ) ); + } + } + + public void doPost( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + String queryString = req.getQueryString(); + res.setContentType( "text/html" ); + + // Info de marcacao + // Dados que vem no pedido: marcacao_tipo, data, hora + Hashtable parameters = parseParameters( new Hashtable( req.getParameterMap() ) ); + + // Ir buscar o resto dos parametros à sessão + HttpSession session = req.getSession( false ); + if( session == null ) + { + // timeout + out.println( showPage( "marcacao/marcacao_sessao_expirou.html", null ) ); + return; + } + + parameters.put( EMPRESA, session.getAttribute( siprpServlet.sessionCompanyName ) ); + parameters.put( ESTABELECIMENTO, session.getAttribute( "session_estabelecimento_nome" ) ); + parameters.put( FUNCIONARIO, session.getAttribute( "session_funcionario_nome" ) ); + //parameters.put( session.getAttribute( "session_funcionario_numero" ) ); + + String from = ( String ) session.getAttribute( siprpServlet.sessionCompanyEmail ); + + String marcacao_tipo = ( String )parameters.get( MARCACAO_TIPO ); + + String email = DEFAULT_EMAIL; + if( PROPERTIES != null && PROPERTIES.containsKey( EMAIL_MARCACAO ) ) + { + email = ( String ) PROPERTIES.get( EMAIL_MARCACAO ); + } + String destination = email; + String subject = "Pedido de marca\u00e7\u00e3o de " + marcacao_tipo + " via web"; + String content = createContent( parameters, FORM_FIELDS, "marcacao/marcacao.html" ); + // manda mail + boolean success = sendMail( from, destination, subject, content, true ); + + // mostra pagina correspondente + out.println( showResultPage( success, "marcacao/marcacao_enviada.html", "marcacao/marcacao_nao_enviada.html" ) ); + } + + private String showPage( String page, Hashtable parameters ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + if( parameters != null ) + { + String key; + for( Enumeration e = parameters.keys(); e.hasMoreElements(); ) + { + key = ( String ) e.nextElement(); + context.put( key, parameters.get( key ) ); + } + } + + Velocity.mergeTemplate( page, Velocity.ENCODING_DEFAULT, context, output ); + + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + + return null; + } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEmpresas.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEmpresas.java new file mode 100644 index 00000000..60303b2f --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEmpresas.java @@ -0,0 +1,113 @@ +package siprp.pagina; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.strings.*; +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +public class doGetListaEmpresas extends siprpServlet{ + + /** Creates a new instance of doGetListaEmpresas */ + public doGetListaEmpresas(HttpServletRequest req, HttpServletResponse res) throws IOException + { + ServletOutputStream out = res.getOutputStream(); + Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery; + String userRole="", temp=""; + HttpSession session = req.getSession(false); + Vector links = new Vector(); + Vector desc = new Vector(); +String empresa_nome; + try + { + userRole = (String)session.getAttribute(super.sessionUserRole); +empresa_nome = ( String ) session.getAttribute( sessionCompanyName ); + + if (userRole == null) + { + throw new IllegalStateException(); + } + + if ( userRole.equals ( super.superUserRole ) ) + { +empresa_nome = null; + Class.forName(super.bdDriver); + con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT id, designacao_social, designacao_social_plain FROM empresas WHERE inactivo <> 'y' ORDER BY designacao_social_plain" ); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + + int index=0; + int max = rs.columnLength(); + + while ( index < max ) + { + String str = (String)rs.get(index,1); + if( str != null && str.trim().length() > 0 ) + { + temp=""+rs.get(index,0); // converter de int para String + dbQuery = new StringBuffer(); + dbQuery.append("/"+super.servletName+"/?"+temp); // contruir url + links.add(dbQuery.toString()); + desc.add((String)rs.get(index,1)); + } + ++index; + } + stmt.close(); + con.close(); + + +session.setAttribute( sessionEstabelecimentoId, null ); + +HashMap hmValues = new HashMap(); +//hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); +hmValues.put( "empresa_nome", empresa_nome ); +hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); +hmValues.put( "estabelecimento_id", session.getAttribute( sessionEstabelecimentoId ) ); +hmValues.put( "userRole", userRole ); +hmValues.put( "userName", session.getAttribute( sessionUser ) ); +hmValues.put( msgTemplate , super.msgListaEmpresas ) ; +hmValues.put( templateUserRole, userRole); +hmValues.put( templateQuery, super.queryStringEmpresas ); +hmValues.put( templateVector1,links); +hmValues.put( templateVector2,desc); +hmValues.put( templateVector3,null); +out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + + + //out.println( mergeTemplate( super.msgListaEmpresas, userRole, super.queryStringEmpresas, links, desc, null, super.authenticatedUserTemplate) ); + + } + else + { + out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); + } + + } + catch ( IllegalStateException e ) // session timeout + { + e.printStackTrace(); + out.println( mergeTemplate(msgSessionTimeout, super.errorTemplate) ); + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , userRole, super.errorTemplate) ); + } + } + +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEstabelecimentos.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEstabelecimentos.java new file mode 100644 index 00000000..4e8b9642 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaEstabelecimentos.java @@ -0,0 +1,105 @@ +package siprp.pagina; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.strings.*; +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +public class doGetListaEstabelecimentos extends siprpServlet{ + + /** Creates a new instance of doGetListaEstabelecimentos */ + public doGetListaEstabelecimentos(HttpServletRequest req, HttpServletResponse res) throws IOException + { + ServletOutputStream out = res.getOutputStream(); + Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery, sBuffer; + String userRole, empresaId, temp; + HttpSession session = req.getSession(false); + Vector links = new Vector(); + Vector desc = new Vector(); + try + { + userRole = (String)session.getAttribute(super.sessionUserRole); + empresaId = (String)session.getAttribute(super.sessionEmpresaId); + + if ( userRole.equals ( super.superUserRole ) || userRole.equals ( empresaId ) ) + { + Class.forName(super.bdDriver); + con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); + dbQuery = new StringBuffer(); + dbQuery.append( " SELECT id, nome, nome_plain FROM estabelecimentos WHERE inactivo <> 'y' AND empresa_id = '"+empresaId+"' order by nome_plain" ); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + + int index=0; + int max = rs.columnLength(); + + while ( index < max ) + { + temp=""+rs.get(index,0); // converter de int para String + dbQuery = new StringBuffer(); + dbQuery.append("/"+super.servletName+"/?"+empresaId+"/"+temp); // contruir url + links.add(dbQuery.toString()); + desc.add((String)rs.get(index,1)); + ++index; + } + sBuffer = new StringBuffer(); + sBuffer.append(""+super.nomeEmpresa(con,empresaId)+""); + +if( userRole.equals( "manager" ) ) +{ + session.setAttribute( sessionCompanyName, nomeEmpresa( con, ( String ) session.getAttribute( sessionEmpresaId ) ) ); +} +else +{ + session.setAttribute( sessionCompanyName, nomeEmpresa( con, userRole ) ); +} + +session.setAttribute( sessionCompanyEmail, emailEmpresa( con, empresaId ) ); + +session.setAttribute( sessionEstabelecimentoId, null ); + +HashMap hmValues = new HashMap(); +hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); +hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); +hmValues.put( "estabelecimento_id", session.getAttribute( sessionEstabelecimentoId ) ); +hmValues.put( "userRole", userRole ); +hmValues.put( "userName", session.getAttribute( sessionUser ) ); +hmValues.put( msgTemplate , sBuffer.toString() ) ; +hmValues.put( templateUserRole, userRole); +hmValues.put( templateQuery, super.queryStringEstabelecimentos ); +hmValues.put( templateVector1,links); +hmValues.put( templateVector2,desc); +hmValues.put( templateVector3,null); +out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + +// out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringEstabelecimentos, links, desc, null, super.authenticatedUserTemplate) ); + stmt.close(); + con.close(); + } + else + { + out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); + } + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); + } + } + +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadores.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadores.java new file mode 100644 index 00000000..f7d03c60 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadores.java @@ -0,0 +1,299 @@ +package siprp.pagina; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.strings.*; +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +public class doGetListaTrabalhadores extends siprpServlet{ + + /** Creates a new instance of doGetListaTrabalhadores */ + public doGetListaTrabalhadores(HttpServletRequest req, HttpServletResponse res, String query) throws IOException + { + boolean print = false; + if( query != null ) + { + print = query.indexOf( "_print" ) != -1; + if( query.indexOf( "trabalhadores_tudo" ) == 0 ) + { + new doGetListaTrabalhadoresTudo( req, res, print ); + return; + } + else if( query.indexOf( "trabalhadores_pendentes" ) == 0 ) + { + new doGetListaTrabalhadoresPendentes( req, res, print ); + return; + } + } + ServletOutputStream out = res.getOutputStream(); + Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs, rsTrab; + StringBuffer sBuffer; + String userRole, empresaId, estabelecimentoId, temp; + HttpSession session = req.getSession(false); + Vector links = new Vector(); + Vector desc = new Vector(); + Vector descAdicional = new Vector(); + java.util.Date today = new java.util.Date(); + try + { + userRole = (String)session.getAttribute(super.sessionUserRole); + empresaId = (String)session.getAttribute(super.sessionEmpresaId); + estabelecimentoId = (String)session.getAttribute(super.sessionEstabelecimentoId); + + if ( userRole.equals ( super.superUserRole ) || userRole.equals ( empresaId ) ) + { + Class.forName(super.bdDriver); + con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); + if ( super.verificaEstabelecimento(con, empresaId, estabelecimentoId) ) // estabelecimento pertence à empresa ?? + { + //Class.forName(super.bdDriver); + //con = DriverManager.getConnection( super.bdUrl, super.bdUsername, super.bdPassword ); + String dbQuery = "SELECT id, nome, nome_plain FROM trabalhadores WHERE inactivo <> 'y' AND data_demissao IS NULL AND estabelecimento_id = '"+estabelecimentoId+"' ORDER BY nome_plain"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rsTrab = new ResultSet2DArray( stmt.executeQuery( dbQuery ) ); + rsTrab.getObjects(); + stmt.close(); + + final int max = rsTrab.columnLength(); + + for ( int index = 0; index < max; index++ ) + { + Integer id = (Integer)rsTrab.get(index,0); + String link = "/"+super.servletName+"/?"+empresaId+"/"+estabelecimentoId+"/"+id; + links.add(link); + HashMap trabalhador = new HashMap(); + trabalhador.put( "Nome", (String)rsTrab.get(index,1) ); + + + dbQuery = "SELECT id, data, estado FROM marcacoes_trabalhador " + + "WHERE tipo = 1 and trabalhador_id = " + id + + " ORDER BY data DESC"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery ) ); + rs.getObjects(); + stmt.close(); + if( rs.columnLength() > 0 ) + { + java.util.Date dataConsulta2 = ( java.util.Date ) rs.get( 0, 1 ); + Integer estado2 = ( Integer ) rs.get( 0, 2 ); + java.util.Date dataConsulta1; + // java.util.Date dataRelatorio1; + // java.util.Date dataRelatorio2 = (java.util.Date) rs.get( 0, 3 ); + Integer estado1; + String realizada1 = ""; + String realizada2 = ""; + if( rs.columnLength() >= 2 ) + { + dataConsulta1 = ( java.util.Date ) rs.get( 1, 1 ); + estado1 = ( Integer ) rs.get( 1, 2 ); + // dataRelatorio1 = (java.util.Date) rs.get( 1, 3 ); + } + else + { + dataConsulta1 = dataConsulta2; + estado1 = estado2; + // dataRelatorio1 = dataRelatorio2; + } + if( ESTADO_REALIZADO.equals( estado2 ) || today.after( dataConsulta2 ) ) + { + trabalhador.put( "ultima_consulta", dataConsulta2 ); + if( estado2.equals( ESTADO_POR_REALIZAR ) ) + { + realizada2 = "não"; + } + else if( estado2.equals( ESTADO_REALIZADO ) ) + { + realizada2 = "sim"; + } + trabalhador.put( "realizada", realizada2 ); + trabalhador.put( "proxima_consulta", "" ); + } + else + { + try + { + for( int c = 1; c < rs.columnLength(); c++ ) + { + java.util.Date dataTemp = ( java.util.Date ) rs.get( c, 1 ); + dataConsulta1 = dataTemp; + estado1 = ( Integer ) rs.get( c, 2 ); + if( dataTemp.after( today ) ) + { + dataConsulta2 = dataTemp; + } + else + { + break; + } + } + } + catch( Exception ex ) + { + ex.printStackTrace(); + } + trabalhador.put( "proxima_consulta", dataConsulta2 ); + + if( !dataConsulta2.equals( dataConsulta1 ) ) + { + if( estado1.equals( ESTADO_POR_REALIZAR ) ) + { + realizada1 = "não"; + } + else if( estado1.equals( ESTADO_REALIZADO ) ) + { + realizada1 = "sim"; + } + trabalhador.put( "realizada", realizada1 ); + trabalhador.put( "ultima_consulta", dataConsulta1 ); + } + else + { + trabalhador.put( "ultima_consulta", "" ); + trabalhador.put( "realizada", null ); + } + } + } + else + { + trabalhador.put( "ultima_consulta", "" ); + trabalhador.put( "realizada", null ); + trabalhador.put( "proxima_consulta", "" ); + } + + + dbQuery = "SELECT id, data, estado FROM marcacoes_trabalhador " + + "WHERE tipo = 0 and trabalhador_id = " + id + + " ORDER BY data DESC"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery ) ); + rs.getObjects(); + stmt.close(); + if( rs.columnLength() > 0 ) + { + java.util.Date dataConsulta2 = ( java.util.Date ) rs.get( 0, 1 ); + Integer estado2 = ( Integer ) rs.get( 0, 2 ); + Integer estado1; + java.util.Date dataConsulta1; + // java.util.Date dataRelatorio1; + // java.util.Date dataRelatorio2 = (java.util.Date) rs.get( 0, 3 ); + String realizada1 = ""; + String realizada2 = ""; + if( rs.columnLength() >= 2 ) + { + dataConsulta1 = ( java.util.Date ) rs.get( 1, 1 ); + estado1 = ( Integer ) rs.get( 1, 2 ); + // dataRelatorio1 = (java.util.Date) rs.get( 1, 3 ); + } + else + { + dataConsulta1 = dataConsulta2; + estado1 = estado2; + // dataRelatorio1 = dataRelatorio2; + } + if( ESTADO_REALIZADO.equals( estado2 ) || today.after( dataConsulta2 ) ) + { + trabalhador.put( "ultimo_exame", dataConsulta2 ); + if( estado2.equals( ESTADO_POR_REALIZAR ) ) + { + realizada2 = "não"; + } + else if( estado2.equals( ESTADO_REALIZADO ) ) + { + realizada2 = "sim"; + } + trabalhador.put( "realizado", realizada2 ); + trabalhador.put( "proximo_exame", "" ); + } + else + { + trabalhador.put( "proximo_exame", dataConsulta2 ); + if( !dataConsulta2.equals( dataConsulta1 ) ) + { + if( estado1.equals( ESTADO_POR_REALIZAR ) ) + { + realizada1 = "não"; + } + else if( estado1.equals( ESTADO_REALIZADO ) ) + { + realizada1 = "sim"; + } + trabalhador.put( "realizado", realizada1 ); + trabalhador.put( "ultimo_exame", dataConsulta1 ); + } + else + { + trabalhador.put( "ultimo_exame", "" ); + trabalhador.put( "realizado", null ); + } + } + } + else + { + trabalhador.put( "ultimo_exame", "" ); + trabalhador.put( "realizado", null ); + trabalhador.put( "proximo_exame", "" ); + } + + desc.add( trabalhador ); + } + + + sBuffer = new StringBuffer(); + sBuffer.append(""+super.nomeEmpresa(con,empresaId)+"

" + +super.nomeEstabelecimento(con, estabelecimentoId)+"" ); + + HashMap hmValues = new HashMap(); + hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); + hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); + hmValues.put( "estabelecimento_nome", super.nomeEstabelecimento( con, estabelecimentoId ) ); + hmValues.put( "estabelecimento_id", estabelecimentoId ); + hmValues.put( "userRole", userRole ); + hmValues.put( "userName", session.getAttribute( sessionUser ) ); + hmValues.put( msgTemplate , sBuffer.toString() ) ; + hmValues.put( templateUserRole, userRole); + hmValues.put( templateQuery, super.queryStringTrabalhadores ); + hmValues.put( templateVector1,links); + hmValues.put( templateVector2,desc); + hmValues.put( templateVector3,null); + if( !print ) + { + out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + } + else + { + out.println( mergeTemplate( hmValues, super.authenticatedUserPrintTemplate)); + } +// out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringTrabalhadores, links, desc, null, super.authenticatedUserTemplate) ); + } + else // est não pertence à empresa + { + out.println( mergeTemplate( super.msgLinkFormatError , userRole, super.errorTemplate) ); + } + con.close(); + } + else // Role não permite ver esta informação + { + out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); + } + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); + } + } + +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresPendentes.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresPendentes.java new file mode 100644 index 00000000..d6dfde6e --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresPendentes.java @@ -0,0 +1,879 @@ +/* + * doGetListaTrabalhadoresPendentes.java + * + * Created on 22 de Abril de 2005, 15:56 + */ + +package siprp.pagina; + +import java.io.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import java.sql.*; +import java.util.*; + +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.data.*; +import com.evolute.utils.db.*; +import com.evolute.utils.sql.*; +import com.evolute.utils.strings.*; + +/** + * + * @author fpalma + */ +public class doGetListaTrabalhadoresPendentes + extends siprpServlet +{ + private static final long TRES_MESES = 3L * 30L * 24L * 60L * 60L * 1000L; + private static final long CATORZE_DIAS = 14L * 24L * 60L * 60L * 1000L; + + protected static final int ESTADO_NAO_APLICAVEL = 0; + protected static final int ESTADO_PENDENTE = 1; + protected static final int ESTADO_MARCADO = 2; + protected static final int ESTADO_TRATADO = 3; + + protected static int MOTIVO_ADMISSAO = 1; + protected static int MOTIVO_PERIODICA = 2; + protected static int MOTIVO_OCASIONAL = 3; + protected static int MOTIVO_PERIODICA_INICIAL = 5; + + protected static final Hashtable CORES_ESTADOS = new Hashtable(); + protected static final Hashtable TEXTOS_ESTADOS = new Hashtable(); + static + { + CORES_ESTADOS.put( new Integer( ESTADO_NAO_APLICAVEL ), "white" ); + CORES_ESTADOS.put( new Integer( ESTADO_PENDENTE ), "red" ); + CORES_ESTADOS.put( new Integer( ESTADO_MARCADO ), "yellow" ); + CORES_ESTADOS.put( new Integer( ESTADO_TRATADO ), "green" ); + + TEXTOS_ESTADOS.put( new Integer( ESTADO_NAO_APLICAVEL ), "n.a." ); + TEXTOS_ESTADOS.put( new Integer( ESTADO_PENDENTE ), "pendente" ); + TEXTOS_ESTADOS.put( new Integer( ESTADO_MARCADO ), "pendente" ); +// TEXTOS_ESTADOS.put( new Integer( ESTADO_TRATADO ), "green" ); + } + + protected java.sql.Date today; + protected long todayMillis; + + /** Creates a new instance of doGetListaTrabalhadores */ +// public doGetListaTrabalhadoresPendentes(HttpServletRequest req, HttpServletResponse res, boolean print) +// throws IOException +// { +// ServletOutputStream out = res.getOutputStream(); +// Connection con = null ; +// Statement stmt = null ; +// ResultSet2DArray rs; +// StringBuffer dbQuery, sBuffer; +// String userRole, empresaId, estabelecimentoId, temp; +// HttpSession session = req.getSession(false); +// Vector links = new Vector(); +// Vector desc = new Vector(); +// Vector descAdicional = new Vector(); +//// today = new java.util.Date(); +//// todayMillis = today.getTime(); +// +// try +// { +// stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); +// rs = new ResultSet2DArray( stmt.executeQuery( "SELECT CURRENT_DATE" ) ); +// today = ( java.sql.Date ) rs.get( 0, 0 ); +// stmt.close(); +// todayMillis = today.getTime(); +// +// userRole = (String)session.getAttribute(super.sessionUserRole); +// empresaId = (String)session.getAttribute(super.sessionEmpresaId); +// estabelecimentoId = (String)session.getAttribute(super.sessionEstabelecimentoId); +// +// if ( userRole.equals ( super.superUserRole ) || userRole.equals ( empresaId ) ) +// { +// Class.forName(super.bdDriver); +// con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); +// if ( super.verificaEstabelecimento(con, empresaId, estabelecimentoId) ) // estabelecimento pertence à empresa ?? +// { +// //Class.forName(super.bdDriver); +// //con = DriverManager.getConnection( super.bdUrl, super.bdUsername, super.bdPassword ); +// dbQuery = new StringBuffer(); +// dbQuery.append( "SELECT trabalhadores.id, trabalhadores.nome, " +// + "marcacoes_trabalhador.tipo, marcacoes_trabalhador.data, marcacoes_trabalhador.estado, " +// + " trabalhadores.nome_plain, marcacoes_trabalhador.motivo " +// + "FROM trabalhadores LEFT JOIN marcacoes_trabalhador ON ( marcacoes_trabalhador.trabalhador_id = trabalhadores.id )" +// + "WHERE estabelecimento_id = " + estabelecimentoId +// + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL " +// + " AND marcacoes_trabalhador.estado NOT IN ( 3, 4, 5) " +// + "ORDER BY 6, 3, 4 DESC " ); +// // dbQuery.append( "SELECT id, nome, ( ultima_consulta IS NOT NULL AND realizada = 'y' )," +// // + " ( ultimo_exame IS NOT NULL AND realizado = 'y' )," +// // + " proxima_consulta IS NOT NULL, proximo_exame IS NOT NULL, " +// // + " ( proxima_consulta IS NOT NULL AND proxima_consulta - current_date <= 14 ), " +// // + " ( proximo_exame IS NOT NULL AND proximo_exame - current_date <= 14 )" +// // + " FROM trabalhadores " +// // + " WHERE estabelecimento_id = '"+estabelecimentoId+"'" +// // + " AND ( ultima_consulta IS NULL OR realizada = 'n' OR" +// // + " ( proxima_consulta IS NOT NULL AND proxima_consulta - current_date <= 14 )" +// // + " OR ( proximo_exame IS NOT NULL AND proximo_exame - current_date <= 14 ) )" +// // + " ORDER BY nome" ); +// stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); +// rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); +// +// int index=0; +// int max = rs.columnLength(); +// +// Integer trabalhadorID = new Integer( -1 ); +// String nomeTrabalhador = ""; +// Vector consultas = new Vector(); +// Vector exames = new Vector(); +// +// for ( index = 0; index <= max; index++ ) +// { +// Integer id = index < max ? ( Integer ) rs.get( index, 0 ) : new Integer( -1 ); +// if( !id.equals( trabalhadorID ) ) +// { +// Object listaConsultas[][] = ( Object[][] ) consultas.toArray( new Object[consultas.size()][3] ); +// Object listaExames[][] = ( Object[][] ) exames.toArray( new Object[exames.size()][3] ); +// if( trabalhadorID.intValue() > -1 && +// verificarTrabalhador( listaConsultas, listaExames ) ) +// { +// temp=""+rs.get(index - 1,0); // converter de int para String +// dbQuery = new StringBuffer(); +// dbQuery.append("/"+super.servletName+"/?"+empresaId+"/"+estabelecimentoId+"/"+temp); // contruir url +// links.add(dbQuery.toString()); +// desc.add( criarDadosTrabalhador( con, trabalhadorID, nomeTrabalhador, listaConsultas, listaExames ) ); +// } +// exames.clear(); +// consultas.clear(); +// } +// if( index == max ) +// { +// break; +// } +// Integer tipo = ( Integer ) rs.get( index, 2 ); +// +// String nome = ( String ) rs.get( index, 1 ); +// java.util.Date data = ( java.util.Date ) rs.get( index, 3 ); +// Integer estado = ( Integer ) rs.get( index, 4 ); +// Integer motivo = ( Integer ) rs.get( index, 6 ); +// trabalhadorID = id; +// nomeTrabalhador = nome; +// Object marcacao[] = new Object[]{ data, estado, motivo }; +// if( tipo == null ) +// { +// continue; +// } +// switch( tipo.intValue() ) +// { +// case TIPO_MARCACAO_EXAMES: +// exames.add( marcacao ); +// break; +// +// case TIPO_MARCACAO_CONSULTA: +// consultas.add( marcacao ); +// break; +// } +// } +// stmt.close(); +// +// sBuffer = new StringBuffer(); +// sBuffer.append(""+super.nomeEmpresa(con,empresaId)+"

" +// +super.nomeEstabelecimento(con, estabelecimentoId)+"" ); +// +// HashMap hmValues = new HashMap(); +// hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); +// hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); +// hmValues.put( "estabelecimento_nome", super.nomeEstabelecimento( con, estabelecimentoId ) ); +// hmValues.put( "estabelecimento_id", estabelecimentoId ); +// hmValues.put( "userRole", userRole ); +// hmValues.put( "userName", session.getAttribute( sessionUser ) ); +// hmValues.put( msgTemplate , sBuffer.toString() ) ; +// hmValues.put( templateUserRole, userRole); +// hmValues.put( templateQuery, "trabalhadores_pendentes" ); +// hmValues.put( templateVector1,links); +// hmValues.put( templateVector2,desc); +// hmValues.put( templateVector3,null); +// if( !print ) +// { +// out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); +// } +// else +// { +// out.println( mergeTemplate( hmValues, super.authenticatedUserPrintTemplate)); +// } +//// out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringTrabalhadores, links, desc, null, super.authenticatedUserTemplate) ); +// } +// else // est não pertence à empresa +// { +// out.println( mergeTemplate( super.msgLinkFormatError , userRole, super.errorTemplate) ); +// } +// con.close(); +// } +// else // Role não permite ver esta informação +// { +// out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); +// } +// } +// catch ( SQLException e ) +// { +// e.printStackTrace(); +// out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); +// } +// catch ( Exception e ) +// { +// e.printStackTrace(); +// out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); +// } +// } + + public doGetListaTrabalhadoresPendentes(HttpServletRequest req, HttpServletResponse res, boolean print ) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + String userRole, empresaId, estabelecimentoId; + HttpSession session = req.getSession(false); + Vector links = new Vector(); + Vector desc = new Vector(); + Vector descAdicional = new Vector(); +// today = new java.util.Date(); +// todayMillis = today.getTime(); + + try + { + Executer executer = getExecuter(); + Virtual2DArray array = executer.executeQuery( new Select( "SELECT CURRENT_DATE" ) ); + today = ( java.sql.Date ) array.get( 0, 0 ); + todayMillis = today.getTime(); + + userRole = (String)session.getAttribute(sessionUserRole); + empresaId = (String)session.getAttribute(sessionEmpresaId); + estabelecimentoId = (String)session.getAttribute(sessionEstabelecimentoId); + + if ( userRole.equals ( superUserRole ) || userRole.equals ( empresaId ) ) + { + if ( verificaEstabelecimento(null, empresaId, estabelecimentoId) ) // estabelecimento pertence à empresa ?? + { + //Class.forName(super.bdDriver); + //con = DriverManager.getConnection( super.bdUrl, super.bdUsername, super.bdPassword ); + String query = "( SELECT trabalhadores.id, trabalhadores.nome, " + + "marcacoes_trabalhador.tipo, marcacoes_trabalhador.data, marcacoes_trabalhador.estado, " + + " trabalhadores.nome_plain, marcacoes_trabalhador.motivo, marcacoes_trabalhador.data " + + "FROM trabalhadores LEFT JOIN marcacoes_trabalhador ON ( marcacoes_trabalhador.trabalhador_id = trabalhadores.id ) " + + "WHERE estabelecimento_id = " + estabelecimentoId + + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL " + + " AND marcacoes_trabalhador.estado NOT IN ( 3, 4, 5) " + + " AND marcacoes_trabalhador.tipo = " + TIPO_MARCACAO_CONSULTA + + " AND marcacoes_trabalhador.motivo <> " + MOTIVO_OCASIONAL + " )" + + " UNION " + + "( SELECT trabalhadores.id, trabalhadores.nome, " + + "marcacoes_trabalhador.tipo, marcacoes_trabalhador.data, marcacoes_trabalhador.estado, " + + " trabalhadores.nome_plain, marcacoes_trabalhador.motivo, marcacoes_trabalhador.data + 90 " + + "FROM trabalhadores LEFT JOIN marcacoes_trabalhador ON ( marcacoes_trabalhador.trabalhador_id = trabalhadores.id ) " + + "WHERE estabelecimento_id = " + estabelecimentoId + + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL " + + " AND marcacoes_trabalhador.estado NOT IN ( 3, 4, 5) " + + " AND marcacoes_trabalhador.tipo = " + TIPO_MARCACAO_EXAMES + " )" + + "ORDER BY 6, 8, 3 DESC "; + array = executer.executeQuery( new Select( query ) ); + + query = "SELECT trabalhadores.id, trabalhadores.nome, " + + "marcacoes_trabalhador.tipo, marcacoes_trabalhador.data, marcacoes_trabalhador.estado, " + + " trabalhadores.nome_plain, marcacoes_trabalhador.motivo, marcacoes_trabalhador.data " + + "FROM trabalhadores LEFT JOIN marcacoes_trabalhador ON ( marcacoes_trabalhador.trabalhador_id = trabalhadores.id ) " + + "WHERE estabelecimento_id = " + estabelecimentoId + + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL " + + " AND marcacoes_trabalhador.estado NOT IN ( 3, 4, 5) " + + " AND marcacoes_trabalhador.tipo = " + TIPO_MARCACAO_CONSULTA + + " AND marcacoes_trabalhador.motivo = " + MOTIVO_OCASIONAL + + " ORDER BY 6, 8, 3 DESC"; + Virtual2DArray ocasionaisArray = executer.executeQuery( new Select( query ) ); + + query = "SELECT trabalhadores.id, trabalhadores.nome " + + "FROM trabalhadores " + + "WHERE estabelecimento_id = " + estabelecimentoId + + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL;"; + Virtual2DArray trabalhadoresArray = executer.executeQuery( new Select( query ) ); + + Hashtable marcacoesPorID = new Hashtable(); + Hashtable ocasionaisPorID = new Hashtable(); + Hashtable nomesPorID = new Hashtable(); + for( int n = 0; n < trabalhadoresArray.columnLength(); n++ ) + { + nomesPorID.put( trabalhadoresArray.get( n, 0 ), trabalhadoresArray.get( n, 1 ) ); + } + + preencherMarcacoes( array, nomesPorID, marcacoesPorID ); + preencherMarcacoes( ocasionaisArray, nomesPorID, ocasionaisPorID ); + + Integer ids[] = ( Integer[] ) nomesPorID.keySet().toArray( new Integer[0] ); + IDObject trabalhadores[] = new IDObject[ ids.length ]; + for( int n = 0; n < ids.length; n++ ) + { + trabalhadores[ n ] = new MappableObject( ids[ n ], nomesPorID.get( ids[ n ] ) ); + } + Arrays.sort( trabalhadores, new Comparator(){ + public int compare( Object o1, Object o2 ) + { + String nome1 = StringPlainer.convertString( o1.toString() ); + String nome2 = StringPlainer.convertString( o2.toString() ); + return nome1.compareTo( nome2 ); + } + } ); + + for( int n = 0; n < trabalhadores.length; n++ ) + { + Object marcacoes[][]; + if( marcacoesPorID.containsKey( trabalhadores[ n ].getID() ) ) + { + marcacoes = ( Object[][] ) ( ( Vector )marcacoesPorID.get( trabalhadores[ n ].getID() ) ).toArray( new Object[ 0 ][] ); + } + else + { + marcacoes = new Object[0][]; + } + Object ocasionais[][]; + if( ocasionaisPorID.containsKey( trabalhadores[ n ].getID() ) ) + { + ocasionais = ( Object[][] ) ( ( Vector )ocasionaisPorID.get( trabalhadores[ n ].getID() ) ).toArray( new Object[ 0 ][] ); + } + else + { + ocasionais = new Object[ 0 ][]; + } + Object agrupadas[][] = agruparMarcacoes( marcacoes, ocasionais ); + acrescentarTrabalhador( empresaId, estabelecimentoId, + trabalhadores[ n ], null, + agrupadas, links, desc, + perfilTemConsultas( trabalhadores[ n ].getID(), new Integer( empresaId ) ), + perfilTemExames( trabalhadores[ n ].getID(), new Integer( empresaId ) ) ); + } + + HashMap hmValues = new HashMap(); + hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); + hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); + hmValues.put( "estabelecimento_nome", nomeEstabelecimento( null, estabelecimentoId ) ); + hmValues.put( "estabelecimento_id", estabelecimentoId ); + hmValues.put( "userRole", userRole ); + hmValues.put( "userName", session.getAttribute( sessionUser ) ); + hmValues.put( msgTemplate , ""+nomeEmpresa(null,empresaId)+"

" + +nomeEstabelecimento(null, estabelecimentoId)+"" ) ; + hmValues.put( templateUserRole, userRole); + hmValues.put( templateQuery, "trabalhadores_pendentes" ); + hmValues.put( templateVector1,links); + hmValues.put( templateVector2,desc); + hmValues.put( templateVector3,null); + if( !print ) + { + out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + } + else + { + out.println( mergeTemplate( hmValues, super.authenticatedUserPrintTemplate)); + } +// out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringTrabalhadores, links, desc, null, super.authenticatedUserTemplate) ); + } + else // est não pertence à empresa + { + out.println( mergeTemplate( super.msgLinkFormatError , userRole, super.errorTemplate) ); + } + } + else // Role não permite ver esta informação + { + out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); + } + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); + } + } + + protected void preencherMarcacoes( Virtual2DArray array, Hashtable nomesPorID, Hashtable marcacoesPorID ) + { + int max = array.columnLength(); + for( int index = 0; index < max; index++ ) + { + Integer id = index < max ? ( Integer ) array.get( index, 0 ) : new Integer( -1 ); + Integer tipo = ( Integer ) array.get( index, 2 ); + String nome = ( String ) array.get( index, 1 ); + java.util.Date data = ( java.util.Date ) array.get( index, 3 ); + Integer estado = ( Integer ) array.get( index, 4 ); + Integer motivo = ( Integer ) array.get( index, 6 ); + if( !marcacoesPorID.containsKey( id ) ) + { + nomesPorID.put( id, nome ); + marcacoesPorID.put( id, new Vector() ); + } + if( data != null ) + { + Object marcacao[] = new Object[]{ data, estado, motivo, tipo }; + ( ( Vector ) marcacoesPorID.get( id ) ).add( marcacao ); + } + } + } + + protected Object[][] agruparMarcacoes( Object marcacoes[][], Object ocasionais[][] ) + { + long tresMeses = TRES_MESES; + java.util.Date dataExame = null; + Integer estadoExame = null; + java.util.Date dataConsulta = null; + Integer motivoConsulta = null; + Integer estadoConsulta = null; + Object grupo[] = null; + Vector grupos = new Vector(); + + if( marcacoes != null ) + { + for( int n = 0; n < marcacoes.length; n++ ) + { + if( grupo == null ) + { + grupo = new Object[ 5 ]; + dataExame = null; + estadoExame = null; + dataConsulta = null; + motivoConsulta = null; + estadoConsulta = null; + grupos.add( grupo ); + } + + java.util.Date data = ( java.util.Date ) marcacoes[ n ][ 0 ]; + Integer estado = ( Integer ) marcacoes[ n ][ 1 ]; + Integer motivo = ( Integer ) marcacoes[ n ][ 2 ]; + Integer tipo = ( Integer ) marcacoes[ n ][ 3 ]; + switch( tipo.intValue() ) + { + case TIPO_MARCACAO_EXAMES: + if( dataConsulta == null && + ( dataExame == null || estadoExame.intValue() < 2 ) ) + { + dataExame = data; + estadoExame = estado; + } + else if( dataConsulta != null && Math.abs( dataConsulta.getTime() - data.getTime() ) < tresMeses ) + { + dataExame = data; + estadoExame = estado; + } + else + { + grupo = null; + n--; + } + if( grupo != null ) + { + grupo[ 3 ] = dataExame; + grupo[ 4 ] = estadoExame; + } + break; + + case TIPO_MARCACAO_CONSULTA: + if( dataExame == null || Math.abs( dataExame.getTime() - data.getTime() ) < tresMeses ) + { + dataConsulta = data; + estadoConsulta = estado; + motivoConsulta = motivo; + } + else + { + grupo = null; + n--; + } + if( grupo != null ) + { + grupo[ 0 ] = dataConsulta; + grupo[ 1 ] = estadoConsulta; + grupo[ 2 ] = motivoConsulta; + } + break; + } + } + } + if( ocasionais != null ) + { + for( int n = 0; n < ocasionais.length; n++ ) + { + grupo = new Object[ 5 ]; + for( int i = 0; i < 3; i++ ) + { + grupo[ i ] = ocasionais[ n ][ i ]; + } + grupos.add( grupo ); + } + } + + Object agrupadas[][] = ( Object[][] ) grupos.toArray( new Object[ grupos.size() ][] ); + Arrays.sort( agrupadas, new Comparator(){ + public int compare( Object o1, Object o2 ) + { + Object g1[] = ( Object[] ) o1; + Object g2[] = ( Object[] ) o2; + java.util.Date d1 = ( java.util.Date ) ( g1[ 0 ] != null ? g1[ 0 ] : g1[ 3 ] ); + java.util.Date d2 = ( java.util.Date ) ( g2[ 0 ] != null ? g2[ 0 ] : g2[ 3 ] ); + return d2.compareTo( d1 ); + } + } ); + return agrupadas; + } + + protected void acrescentarTrabalhador( String empresaID, String estabelecimentoID, + IDObject trabalhador, java.util.Date dataFicha, + Object marcacoes[][], Vector links, Vector dados, + boolean perfilConsultas, boolean perfilExames ) + { + int estado[] = new int[ 2 ]; + int index = 0; + boolean pendente = false; + if( marcacoes.length == 0 ) + { + estado[ 0 ] = perfilConsultas ? ESTADO_PENDENTE : ESTADO_NAO_APLICAVEL; + estado[ 1 ] = perfilExames ? ESTADO_PENDENTE : ESTADO_NAO_APLICAVEL; + } + else + { + java.util.Date dataConsulta; + java.util.Date dataExame; + index = -1; + for( ; index + 1 < marcacoes.length; index++ ) + { + int n = index + 1; + dataConsulta = ( java.util.Date ) marcacoes[ n ][ 0 ]; + dataExame = ( java.util.Date ) marcacoes[ n ][ 3 ]; + boolean temConsulta = dataConsulta != null; + boolean consultaAntiga = temConsulta && dataConsulta.before( today ); + boolean temExame = dataExame != null; + boolean exameAntigo = temExame && dataExame.before( today ); + + if( ( temConsulta && consultaAntiga && temExame && exameAntigo ) || + ( temConsulta && consultaAntiga && !temExame && !exameAntigo ) || + ( !temConsulta && !consultaAntiga && temExame && exameAntigo ) ) + { + break; + } + } + if( index == -1 ) + { + index = 0; + } +// else if( index < marcacoes.length - 1 ) +// { +// index = 0; +// } + for( ; index < marcacoes.length; index++ ) + { + dataConsulta = ( java.util.Date ) marcacoes[ index ][ 0 ]; + dataExame = ( java.util.Date ) marcacoes[ index ][ 3 ]; + boolean temConsulta = dataConsulta != null; + long diffConsulta = temConsulta ? dataConsulta.getTime() - today.getTime() : 0; + boolean temExame = dataExame != null; + long diffExame = temExame ? dataExame.getTime() - today.getTime() : 0; + if( ( temConsulta && diffConsulta < CATORZE_DIAS ) || ( temExame && diffExame < CATORZE_DIAS ) ) + { + break; + } + } + if( index >= marcacoes.length ) + { + index = marcacoes.length - 1; + } + else + { + if( marcacoes.length > 1 ) + { + dataConsulta = ( java.util.Date ) marcacoes[ index ][ 0 ]; + dataExame = ( java.util.Date ) marcacoes[ index ][ 3 ]; + Calendar calToday = Calendar.getInstance(); + calToday.setTime( today ); + calToday.add( Calendar.YEAR, -2 ); + if( ( dataConsulta != null && dataConsulta.before( calToday.getTime() ) ) + || ( dataConsulta == null && dataExame != null && dataExame.before( calToday.getTime() ) ) ) + { + if( index > 0 ) + { + index--; + } + else + { + pendente = true; + } + } + } + } + dataConsulta = ( java.util.Date ) marcacoes[ index ][ 0 ]; + Integer estadoConsulta = ( Integer ) marcacoes[ index ][ 1 ]; + Integer motivoConsulta = ( Integer ) marcacoes[ index ][ 2 ]; + dataExame = ( java.util.Date ) marcacoes[ index ][ 3 ]; + Integer estadoExame = ( Integer ) marcacoes[ index ][ 4 ]; + if( perfilConsultas ) + { + if( dataConsulta == null || pendente ) + { + estado[ 0 ] = ESTADO_PENDENTE; + } + else if( estadoConsulta == null || estadoConsulta.intValue() != 2 ) + { + estado[ 0 ] = ESTADO_MARCADO; + } + else + { + estado[ 0 ] = ESTADO_TRATADO; + } + } + else + { + estado[ 0 ] = ESTADO_NAO_APLICAVEL; + } + if( perfilExames ) + { + if( dataExame == null || pendente ) + { + if( motivoConsulta != null && motivoConsulta.intValue() != MOTIVO_OCASIONAL ) + { + estado[ 1 ] = ESTADO_PENDENTE; + } + else + { + estado[ 1 ] = ESTADO_NAO_APLICAVEL; + } + } + else if( estadoExame == null || estadoExame.intValue() != 2 ) + { + estado[ 1 ] = ESTADO_MARCADO; + } + else + { + estado[ 1 ] = ESTADO_TRATADO; + } + } + else + { + estado[ 1 ] = ESTADO_NAO_APLICAVEL; + } + } + if( estado[ 0 ] == 1 || estado[ 0 ] == 2 || + estado[ 1 ] == 1 || estado[ 1 ] == 2 ) + { + links.add( "/"+servletName+"/?"+empresaID+"/"+estabelecimentoID+"/"+trabalhador.getID() ); + HashMap dadosTrabalhador = new HashMap(); + dadosTrabalhador.put( "Nome", trabalhador.toString() ); + dadosTrabalhador.put( "Consulta", CORES_ESTADOS.get( new Integer( estado[ 0 ] ) ) ); + Object text = TEXTOS_ESTADOS.get( new Integer( estado[ 0 ] ) ); + dadosTrabalhador.put( "Consulta_estado", text != null ? text : marcacoes[ index ][ 0 ] ); + dadosTrabalhador.put( "Exame", CORES_ESTADOS.get( new Integer( estado[ 1 ] ) ) ); + text = TEXTOS_ESTADOS.get( new Integer( estado[ 1 ] ) ); + dadosTrabalhador.put( "Exame_estado", text != null ? text : marcacoes[ index ][ 3 ] ); + dados.add( dadosTrabalhador ); + } + } + + protected boolean perfilTemConsultas( Integer trabalhadorID, Integer empresaID ) + throws Exception + { + Executer executer = getExecuter(); + String query = "SELECT a_consultas, b_consultas FROM empresas WHERE id = " + empresaID; + Virtual2DArray array = executer.executeQuery( new Select( query ) ); + boolean consultas[] = new boolean[]{ "y".equals( array.get( 0, 0 ) ), "n".equals( array.get( 0, 0 ) ) }; + query = "SELECT perfil FROM trabalhadores WHERE id = " + trabalhadorID; + array = executer.executeQuery( new Select( query ) ); + Integer perfil = ( Integer )array.get( 0, 0 ); + if( perfil != null ) + { + return consultas[ perfil.intValue() - 1 ]; + } + else + { + return false; + } + } + + protected boolean perfilTemExames( Integer trabalhadorID, Integer empresaID ) + throws Exception + { + Executer executer = getExecuter(); + String query = "SELECT a_exames, b_exames FROM empresas WHERE id = " + empresaID; + Virtual2DArray array = executer.executeQuery( new Select( query ) ); + boolean consultas[] = new boolean[]{ "y".equals( array.get( 0, 0 ) ), "n".equals( array.get( 0, 0 ) ) }; + query = "SELECT perfil FROM trabalhadores WHERE id = " + trabalhadorID; + array = executer.executeQuery( new Select( query ) ); + Integer perfil = ( Integer )array.get( 0, 0 ); + if( perfil != null ) + { + return consultas[ perfil.intValue() - 1 ]; + } + else + { + return false; + } + } + +// protected boolean verificarTrabalhador( Object consultas[][], Object exames[][] ) +// { +// boolean estadoConsultas = false; +// boolean estadoExames = ( exames.length == 0 ) || ( ( java.util.Date )exames[ 0 ][ 0 ] ).before(today) || +// ( ( ( ( java.util.Date )exames[ 0 ][ 0 ] ).getTime() - todayMillis ) / 86400000 > 14 ); +// if( consultas.length > 0 ) +// { +// int anterior; +// int proxima; +// if( ( (java.util.Date) consultas[ 0 ][ 0 ] ).after( today ) ) +// { +// proxima = 0; +// if( consultas.length >= 2 ) +// { +// anterior = 1; +// } +// else +// { +// anterior = -1; +// } +// } +// else +// { +// proxima = -1; +// anterior = 0; +// } +// estadoConsultas = anterior >= 0 && "y".equals( consultas[ anterior ][ 1 ] ) && +// ( proxima == -1 || ( ( ( java.util.Date )consultas[ proxima ][ 0 ] ).getTime() - todayMillis ) / 86400000 > 14 ); +// } +// return !(estadoConsultas && estadoExames); +// } + +// protected HashMap criarDadosTrabalhador( Integer id, String nome, +// Object consultas[][], Object exames[][] ) +// throws Exception +// { +//// dbQuery.append( "SELECT id, nome, ( ultima_consulta IS NOT NULL AND realizada = 'y' )," +//// + " ( ultimo_exame IS NOT NULL AND realizado = 'y' )," +//// + " proxima_consulta IS NOT NULL, proximo_exame IS NOT NULL, " +//// + " ( proxima_consulta IS NOT NULL AND proxima_consulta - current_date <= 14 ), " +//// + " ( proximo_exame IS NOT NULL AND proximo_exame - current_date <= 14 )" +//// + " FROM trabalhadores " +//// + " WHERE estabelecimento_id = '"+estabelecimentoId+"'" +//// + " AND ( ultima_consulta IS NULL OR realizada = 'n' OR" +//// + " ( proxima_consulta IS NOT NULL AND proxima_consulta - current_date <= 14 )" +//// + " OR ( proximo_exame IS NOT NULL AND proximo_exame - current_date <= 14 ) )" +//// + " ORDER BY nome" ); +// HashMap trabalhador = new HashMap(); +// trabalhador.put( "Nome", nome ); +// boolean uc = false; +// boolean ue = false; +// boolean pc = false; +// boolean pe = false; +// boolean quase_c = false; +// boolean quase_e = false; +// java.util.Date consultaAnterior = null; +// java.util.Date exameAnterior = null; +// if( consultas.length > 0 ) +// { +// int anterior; +// int proxima; +// if( ( (java.util.Date) consultas[ 0 ][ 0 ] ).after( today ) ) +// { +// proxima = 0; +// if( consultas.length >= 2 ) +// { +// anterior = 1; +// } +// else +// { +// anterior = -1; +// } +// } +// else +// { +// proxima = -1; +// anterior = 0; +// } +// long diff = proxima > -1 ? ( ( ( java.util.Date )consultas[ proxima ][ 0 ] ).getTime() - todayMillis ) / 86400000 : 15; +// uc = anterior > -1 && "y".equals( consultas[ anterior ][ 1 ] ); +// if( uc ) +// { +// consultaAnterior = ( java.util.Date ) consultas[ anterior ][ 0 ]; +// } +// pc = proxima > -1; +// quase_c = pc && diff <= 14; +// } +// +// if( exames.length > 0 ) +// { +// int anterior; +// int proximo; +// if( ( (java.util.Date) exames[ 0 ][ 0 ] ).after( today ) ) +// { +// proximo = 0; +// if( exames.length >= 2 ) +// { +// anterior = 1; +// } +// else +// { +// anterior = -1; +// } +// } +// else +// { +// proximo = -1; +// anterior = 0; +// } +// long diff = proximo > -1 ? ( ( ( java.util.Date )exames[ proximo ][ 0 ] ).getTime() - todayMillis ) / 86400000 : 15; +// ue = anterior > -1 && "y".equals( exames[ anterior ][ 1 ] ); +// if( ue ) +// { +// exameAnterior = ( java.util.Date ) exames[ anterior ][ 0 ]; +// } +// pe = proximo > -1; +// quase_e = pe && diff <= 14; +// } +// +// if( quase_c ) +// { +// trabalhador.put( "Consulta", "yellow" ); +// trabalhador.put( "Consulta_estado", "pendente" ); +// } +// else if( uc ) +// { +// trabalhador.put( "Consulta", "green" ); +// trabalhador.put( "Consulta_estado", consultaAnterior ); +// } +// else if( pc ) +// { +// trabalhador.put( "Consulta", "yellow" ); +// trabalhador.put( "Consulta_estado", "pendente" ); +// } +// else +// { +// trabalhador.put( "Consulta", "red" ); +// trabalhador.put( "Consulta_estado", "pendente" ); +// } +// +// if( quase_e ) +// { +// trabalhador.put( "Exame", "yellow" ); +// trabalhador.put( "Exame_estado", "pendente" ); +// } +// else if( ue ) +// { +// trabalhador.put( "Exame", "green" ); +// trabalhador.put( "Exame_estado", exameAnterior ); +// } +// else if( pe ) +// { +// trabalhador.put( "Exame", "yellow" ); +// trabalhador.put( "Exame_estado", "pendente" ); +// } +// else +// { +// trabalhador.put( "Exame", "red" ); +// trabalhador.put( "Exame_estado", "pendente" ); +// } +// return trabalhador; +// } +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresTudo.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresTudo.java new file mode 100644 index 00000000..2a6d5d28 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetListaTrabalhadoresTudo.java @@ -0,0 +1,255 @@ +/* + * doGetListaTrabalhadoresTudo.java + * + * Created on 21 de Abril de 2005, 17:35 + */ + +package siprp.pagina; + +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; + +import org.apache.velocity.*; +import org.apache.velocity.app.*; + + +import com.evolute.utils.arrays.*; +import com.evolute.utils.db.*; +import com.evolute.utils.sql.*; +import com.evolute.utils.strings.*; +/** + * + * @author fpalma + */ +public class doGetListaTrabalhadoresTudo + extends siprpServlet + implements GlobalConstants +{ + protected java.util.Date today; + protected long todayMillis; + + /** Creates a new instance of doGetListaTrabalhadores */ + public doGetListaTrabalhadoresTudo(HttpServletRequest req, HttpServletResponse res, boolean print) throws IOException + { + ServletOutputStream out = res.getOutputStream(); + Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery, sBuffer; + String userRole, empresaId, estabelecimentoId, temp; + HttpSession session = req.getSession(false); + Vector links = new Vector(); + Vector desc = new Vector(); + Vector descAdicional = new Vector(); + today = new java.util.Date(); + todayMillis = today.getTime(); + + try + { + userRole = (String)session.getAttribute(super.sessionUserRole); + empresaId = (String)session.getAttribute(super.sessionEmpresaId); + estabelecimentoId = (String)session.getAttribute(super.sessionEstabelecimentoId); + + if ( userRole.equals ( super.superUserRole ) || userRole.equals ( empresaId ) ) + { + Class.forName(super.bdDriver); + con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); + if ( super.verificaEstabelecimento(con, empresaId, estabelecimentoId) ) // estabelecimento pertence à empresa ?? + { + //Class.forName(super.bdDriver); + //con = DriverManager.getConnection( super.bdUrl, super.bdUsername, super.bdPassword ); + dbQuery = new StringBuffer(); +// dbQuery.append( "SELECT id, nome, data_ficha FROM trabalhadores " +// + "WHERE estabelecimento_id = '"+estabelecimentoId+"'" +// + " AND ultima_consulta IS NOT NULL AND realizada = 'y' AND" +// + " ( proxima_consulta IS NULL OR proxima_consulta - current_date > 14 )" +// + " AND ( proximo_exame IS NULL OR proximo_exame - current_date > 14 )" +// + " ORDER BY nome" ); + dbQuery.append( "SELECT trabalhadores.id, trabalhadores.nome, " + + "marcacoes_trabalhador.tipo, marcacoes_trabalhador.data, marcacoes_trabalhador.estado, " + + " trabalhadores.nome_plain " + + "FROM trabalhadores, marcacoes_trabalhador " + + "WHERE estabelecimento_id = " + estabelecimentoId + + " AND marcacoes_trabalhador.trabalhador_id = trabalhadores.id " + + " AND trabalhadores.inactivo <> 'y' AND data_demissao IS NULL " + + "ORDER BY 6, 3, 4 DESC " ); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + + int index=0; + int max = rs.columnLength(); + + Integer trabalhadorID = new Integer( -1 ); + String nomeTrabalhador = ""; + Vector consultas = new Vector(); + Vector exames = new Vector(); + + for ( index = 0; index <= max; index++ ) + { + Integer id = index < max ? ( Integer ) rs.get( index, 0 ) : new Integer( -1 ); + if( !id.equals( trabalhadorID ) ) + { + Object listaConsultas[][] = ( Object[][] ) consultas.toArray( new Object[consultas.size()][2] ); + Object listaExames[][] = ( Object[][] ) exames.toArray( new Object[exames.size()][2] ); + if( trabalhadorID.intValue() > -1 && + verificarTrabalhador( listaConsultas, listaExames ) ) + { + temp=""+rs.get(index - 1,0); // converter de int para String + java.util.Date dataUltimaConsulta = null; + for( int c = 0; c < listaConsultas.length; c++ ) + { + if( new Integer( 2 ).equals( listaConsultas[ c ][ 1 ] ) ) + { + dataUltimaConsulta = ( java.util.Date ) listaConsultas[ c ][ 0 ]; + break; + } + } + HashMap dadosTrabalhador = criarDadosTrabalhador( trabalhadorID, nomeTrabalhador, dataUltimaConsulta ); + if( dadosTrabalhador != null ) + { + dbQuery = new StringBuffer(); + dbQuery.append("/"+super.servletName+"/?"+empresaId+"/"+estabelecimentoId+"/"+temp); // construir url + links.add(dbQuery.toString()); + desc.add( dadosTrabalhador ); + } + } + exames.clear(); + consultas.clear(); + } + if( index == max ) + { + break; + } + Integer tipo = ( Integer ) rs.get( index, 2 ); + String nome = ( String ) rs.get( index, 1 ); + java.util.Date data = ( java.util.Date ) rs.get( index, 3 ); + Integer estado = ( Integer ) rs.get( index, 4 ); + trabalhadorID = id; + nomeTrabalhador = nome; + Object marcacao[] = new Object[]{ data, estado }; + switch( tipo.intValue() ) + { + case TIPO_MARCACAO_EXAMES: + exames.add( marcacao ); + break; + + case TIPO_MARCACAO_CONSULTA: + consultas.add( marcacao ); + break; + } + } + stmt.close(); + + sBuffer = new StringBuffer(); + sBuffer.append(""+super.nomeEmpresa(con,empresaId)+"

" + +super.nomeEstabelecimento(con, estabelecimentoId)+"" ); + + HashMap hmValues = new HashMap(); + hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); + hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); + hmValues.put( "estabelecimento_nome", super.nomeEstabelecimento( con, estabelecimentoId ) ); + hmValues.put( "estabelecimento_id", estabelecimentoId ); + hmValues.put( "userRole", userRole ); + hmValues.put( "userName", session.getAttribute( sessionUser ) ); + hmValues.put( msgTemplate , sBuffer.toString() ) ; + hmValues.put( templateUserRole, userRole); + hmValues.put( templateQuery, "trabalhadores_tudo" ); + hmValues.put( templateVector1,links); + hmValues.put( templateVector2,desc); + hmValues.put( templateVector3,null); + if( !print ) + { + out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + } + else + { + out.println( mergeTemplate( hmValues, super.authenticatedUserPrintTemplate)); + } +// out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringTrabalhadores, links, desc, null, super.authenticatedUserTemplate) ); + } + else // est não pertence à empresa + { + out.println( mergeTemplate( super.msgLinkFormatError , userRole, super.errorTemplate) ); + } + con.close(); + } + else // Role não permite ver esta informação + { + out.println( mergeTemplate( super.msgAcessoNegado , userRole, super.errorTemplate) ); + } + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); + } + } + + protected boolean verificarTrabalhador( Object consultas[][], Object exames[][] ) + { + boolean estadoConsultas = false; + boolean estadoExames = ( exames.length == 0 ) || ( ( java.util.Date )exames[ 0 ][ 0 ] ).before(today) || + ( ( ( ( java.util.Date )exames[ 0 ][ 0 ] ).getTime() - todayMillis ) / 86400000 > 14 ); + if( consultas.length > 0 ) + { + int anterior; + int proxima; + if( ( (java.util.Date) consultas[ 0 ][ 0 ] ).after( today ) ) + { + proxima = 0; + if( consultas.length >= 2 ) + { + anterior = 1; + } + else + { + anterior = -1; + } + } + else + { + proxima = -1; + anterior = 0; + } + estadoConsultas = anterior >= 0 && new Integer( 2 ).equals( consultas[ anterior ][ 1 ] ) && + ( proxima == -1 || ( ( ( java.util.Date )consultas[ proxima ][ 0 ] ).getTime() - todayMillis ) / 86400000 > 14 ); + } + return estadoConsultas && estadoExames; + } + + protected HashMap criarDadosTrabalhador( Integer id, String nome, java.util.Date ultimaConsulta ) + throws Exception + { + Executer executer = getExecuter(); + HashMap trabalhador = new HashMap(); + trabalhador.put( "Nome", nome ); + Select select = + new Select( new String[]{ "exames" }, new String[]{ "data" }, + new Field( "trabalhador_id" ).isEqual( id ).and( + new Field( "data" ).isGreaterOrEqual( ultimaConsulta ) ), + new String[]{ "data" }, null ); + +// Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); +// ResultSet2DArray rs = new ResultSet2DArray( stmt.executeQuery( select.toString() ) ); + Virtual2DArray rs = executer.executeQuery( select ); + Object data_ficha = rs.columnLength() > 0 ? rs.get( 0, 0 ) : null; +// stmt.close(); + if( data_ficha == null ) + { + return null; +// data_ficha = ""; + } + trabalhador.put( "Data", data_ficha ); + return trabalhador; + } +} + diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetTrabalhador.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetTrabalhador.java new file mode 100644 index 00000000..267421e7 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doGetTrabalhador.java @@ -0,0 +1,324 @@ +package siprp.pagina; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.strings.*; +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +public class doGetTrabalhador extends siprpServlet +{ + + /** Creates a new instance of doGetTrabalhador */ + public doGetTrabalhador(HttpServletRequest req, HttpServletResponse res) throws IOException + { + ServletOutputStream out = res.getOutputStream(); + Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery, sBuffer; + String userRole, empresaId, estabelecimentoId, trabalhadorId, temp; + HttpSession session = req.getSession(false); + Vector names = new Vector(); + Vector values = new Vector(); + java.util.Date today = new java.util.Date(); + + try + { + userRole = (String)session.getAttribute(super.sessionUserRole); + empresaId = (String)session.getAttribute(super.sessionEmpresaId); + estabelecimentoId = (String)session.getAttribute(super.sessionEstabelecimentoId); + trabalhadorId = (String)session.getAttribute(super.sessionTrabalhadorId); + + Class.forName(super.bdDriver); + con = DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ); + + if ( ( userRole.equals ( super.superUserRole ) || userRole.equals ( empresaId ) ) + && super.verificaEstabelecimento(con, empresaId, estabelecimentoId) + && super.verificaTrabalhador(con, estabelecimentoId, trabalhadorId) ) + { + + dbQuery = new StringBuffer(); + dbQuery.append( " SELECT sexo, categoria, data_nascimento, nome, numero_mecanografico " + + "FROM trabalhadores where id='"+trabalhadorId+"'"); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + + // int index=0; + // int max = super.trabalhadorDescFields.length; + + HashMap hmFuncionario = new HashMap(); + if( rs.columnLength() > 0 ) + { + String tmp; + hmFuncionario.put( "sexo", rs.get( 0, "sexo" ) ); + hmFuncionario.put( "categoria", rs.get( 0, "categoria" ) ); + hmFuncionario.put( "data_nascimento", rs.get( 0, "data_nascimento" ) ); + hmFuncionario.put( "nome", rs.get( 0, "nome" ) ); + hmFuncionario.put( "numero", rs.get( 0, "numero_mecanografico" ) ); + stmt.close(); + + String query = "SELECT id, data, estado, data_relatorio FROM marcacoes_trabalhador " + + "WHERE tipo = 0 and trabalhador_id = " + trabalhadorId + + " ORDER BY data DESC"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + if( rs.columnLength() > 0 ) + { + java.util.Date dataExame2 = ( java.util.Date ) rs.get( 0, 1 ); + Integer estado1; + Integer estado2 = ( Integer ) rs.get( 0, 2 ); + java.util.Date dataExame1; + String realizado1 = ""; + String realizado2 = ""; + if( rs.columnLength() > 1 ) + { + dataExame1 = ( java.util.Date ) rs.get( 1, 1 ); + estado1 = ( Integer ) rs.get( 1, 2 ); + } + else + { + dataExame1 = dataExame2; + estado1 = estado2; + } + if( ESTADO_REALIZADO.equals( estado2 ) || ESTADO_PARCIALMENTE_REALIZADO.equals( estado2 ) + || today.after( dataExame2 ) ) + { + hmFuncionario.put( "ultimo_exame", dataExame2 ); + if( estado2.equals( ESTADO_REALIZADO ) || estado2.equals( ESTADO_PARCIALMENTE_REALIZADO ) ) + { + realizado2 = "sim"; + } + else + { + realizado2 = "não"; + } + hmFuncionario.put( "realizado", realizado2 ); + hmFuncionario.put( "proximo_exame", null ); + } + else + { + hmFuncionario.put( "proximo_exame", dataExame2 ); + if( !dataExame2.equals( dataExame1 ) ) + { + hmFuncionario.put( "ultimo_exame", dataExame1 ); + if( estado1.equals( ESTADO_REALIZADO ) || estado1.equals( ESTADO_PARCIALMENTE_REALIZADO ) ) + { + realizado1 = "sim"; + } + else + { + realizado1 = "não"; + } + hmFuncionario.put( "realizado", realizado1 ); + } + else + { + hmFuncionario.put( "ultimo_exame", null ); + hmFuncionario.put( "realizado", null ); + } + } + } + else + { + hmFuncionario.put( "ultimo_exame", null ); + hmFuncionario.put( "realizado", null ); + hmFuncionario.put( "proximo_exame", null ); + } + stmt.close(); + + query = "SELECT MAX(id) FROM exames WHERE trabalhador_id = " + trabalhadorId + " AND inactivo <> 'y'"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + Integer fichaId = null; + if( rs.columnLength() > 0 ) + { + fichaId = ( Integer ) rs.get( 0, 0 ); + } + stmt.close(); + + if( fichaId != null ) + { + query = "SELECT data, resultado FROM exames WHERE id = " + fichaId; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + Integer resultadoFicha = (Integer) rs.get( 0, 1 ); + stmt.close(); + if( resultadoFicha != null ) + { + switch( resultadoFicha.intValue() ) + { + case 1: + hmFuncionario.put( "resultado", "Apto" ); + break; + case 2: + hmFuncionario.put( "resultado", "Apto Condicionalmente" ); + break; + case 3: + hmFuncionario.put( "resultado", "Inapto Temporariamente" ); + break; + case 4: + hmFuncionario.put( "resultado", "Inapto Definitivamente" ); + break; + default: + hmFuncionario.put( "resultado", null ); + } + } + else + { + hmFuncionario.put( "resultado", null ); + } + } + else + { + hmFuncionario.put( "resultado", null ); + } + + query = "SELECT id, data, estado FROM marcacoes_trabalhador " + + "WHERE tipo = 1 and trabalhador_id = " + trabalhadorId + + " ORDER BY data DESC"; + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + if( rs.columnLength() > 0 ) + { + java.util.Date dataConsulta2 = ( java.util.Date ) rs.get( 0, 1 ); + Integer estado1; + Integer estado2 = ( Integer ) rs.get( 0, 2 ); + java.util.Date dataConsulta1; +// java.util.Date dataRelatorio1; +// java.util.Date dataRelatorio2 = (java.util.Date) rs.get( 0, 3 ); + String realizada1 = ""; + String realizada2 = ""; + if( rs.columnLength() >= 2 ) + { + dataConsulta1 = ( java.util.Date ) rs.get( 1, 1 ); + estado1 = ( Integer ) rs.get( 1, 2 ); +// dataRelatorio1 = (java.util.Date) rs.get( 1, 3 ); + } + else + { + dataConsulta1 = dataConsulta2; + estado1 = estado2; +// dataRelatorio1 = dataRelatorio2; + } + if( ESTADO_REALIZADO.equals( estado2 ) || today.after( dataConsulta2 ) ) + { + hmFuncionario.put( "ultima_consulta", dataConsulta2 ); + if( estado2.equals( ESTADO_REALIZADO ) ) + { + realizada2 = "sim"; + } + else + { + realizada2 = "não"; + } + hmFuncionario.put( "realizada", realizada2 ); + hmFuncionario.put( "proxima_consulta", null ); + } + else + { + try + { + for( int c = 1; c < rs.columnLength(); c++ ) + { + java.util.Date dataTemp = ( java.util.Date ) rs.get( c, 1 ); + dataConsulta1 = dataTemp; + estado1 = ( Integer ) rs.get( c, 2 ); + if( dataTemp.after( today ) ) + { + dataConsulta2 = dataTemp; + } + else + { + break; + } + } + } + catch( Exception ex ) + { + ex.printStackTrace(); + } + hmFuncionario.put( "proxima_consulta", dataConsulta2 ); + if( !dataConsulta2.equals( dataConsulta1 ) ) + { + if( estado1.equals( ESTADO_REALIZADO ) ) + { + realizada1 = "sim"; + } + else + { + realizada1 = "não"; + } + hmFuncionario.put( "realizada", realizada1 ); + hmFuncionario.put( "ultima_consulta", dataConsulta1 ); + } + else + { + hmFuncionario.put( "ultima_consulta", null ); + hmFuncionario.put( "realizada", null ); + } + } + } + else + { + hmFuncionario.put( "ultima_consulta", null ); + hmFuncionario.put( "realizada", null ); + hmFuncionario.put( "proxima_consulta", null ); + } + stmt.close(); + } + + sBuffer = new StringBuffer(); + sBuffer.append(""+super.nomeEmpresa(con,empresaId)+"

" + +super.nomeEstabelecimento(con, estabelecimentoId)+"" ); + + HashMap hmValues = new HashMap(); + hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); + hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); + hmValues.put( "estabelecimento_nome", super.nomeEstabelecimento( con, estabelecimentoId ) ); + + /*Dados para marcacao de consulta/exame*/ + session.setAttribute( "session_estabelecimento_nome", hmValues.get( "estabelecimento_nome" ) ); + session.setAttribute( "session_funcionario_nome", hmFuncionario.get( "nome" ) ); + session.setAttribute( "session_funcionario_numero", hmFuncionario.get( "numero" ) ); + + hmValues.put( "estabelecimento_id", estabelecimentoId ); + hmValues.put( "userRole", userRole ); + hmValues.put( "userName", session.getAttribute( sessionUser ) ); + hmValues.put( msgTemplate , sBuffer.toString() ) ; + hmValues.put( templateUserRole, userRole); + hmValues.put( templateQuery, super.queryStringTrabalhador ); + hmValues.put( "funcionario", hmFuncionario ); + //hmValues.put( templateVector1,names); + //hmValues.put( templateVector2,values); + //hmValues.put( templateVector3,null); + out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + + // out.println( mergeTemplate( sBuffer.toString(), userRole, super.queryStringTrabalhador, names, values, null, super.authenticatedUserTemplate) ); + + } + else + { + out.println( mergeTemplate( super.msgLinkFormatError , userRole, super.errorTemplate) ); + } + con.close(); + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgErroBd , super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( super.msgGenericError , super.errorTemplate) ); + } + + } + +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/doPostLogin.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/doPostLogin.java new file mode 100644 index 00000000..e9c41eec --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/doPostLogin.java @@ -0,0 +1,122 @@ +package siprp.pagina; + +import com.evolute.utils.arrays.*; +import com.evolute.utils.strings.*; +import java.io.*; +import java.util.*; +import java.sql.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +public class doPostLogin extends siprpServlet +{ + + /** Creates a new instance of doPostLogin */ + public doPostLogin(HttpServletRequest req, HttpServletResponse res) throws IOException + { +System.out.println( "doPostLogin()" ); + ServletOutputStream out = res.getOutputStream(); + StringBuffer dbQuery; + ResultSet2DArray rs; + Connection con = null ; + Statement stmt = null ; + String user, userRole, password; + + try + { + user = req.getParameter("user"); + password = req.getParameter("password"); + + if (user.equals("")) + { + out.println( mergeTemplate( msgErroNoUser, errorTemplate) ); + } + else + { + Class.forName(bdDriver); + con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword ); + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT password FROM users WHERE username = '"+user+"'"); + + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + + + if ( rs.columnLength() > 0 && password.equals((String)rs.get(0,0))) + { + // Obter Role + + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT role FROM roles WHERE username = '"+user+"'"); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + userRole = (String)rs.get(0,0); + + // UPDATE HTTP SESSION + HttpSession session = req.getSession(true); + session.setMaxInactiveInterval(sessionTimeout); + + session.setAttribute(sessionUser, user); + session.setAttribute(sessionUserRole, userRole); + session.setAttribute(sessionPassword, password); + + HashMap hmValues = new HashMap(); + session.setAttribute( sessionEmpresaId, userRole ); + if( userRole.equals( "manager" ) ) + { + // session.setAttribute( sessionCompanyName, nomeEmpresa( con, "" + session.getAttribute( sessionEmpresaId ) ) ); + session.setAttribute( sessionCompanyName, null ); + session.setAttribute( sessionEstabelecimentoId, null ); + //hmValues.put( templateQuery, super.queryStringEmpresas ); + new doGetListaEmpresas( req, res ); + } + else + { + session.setAttribute( sessionCompanyName, + nomeEmpresa( DriverManager.getConnection( bdLocalUrl, bdLocalUsername, bdLocalPassword ), + userRole ) ); + session.setAttribute( sessionEstabelecimentoId, "-1" ); + //hmValues.put( templateQuery, super.queryStringEstabelecimentos ); + new doGetListaEstabelecimentos( req, res ); + } + stmt.close(); + con.close(); + + hmValues.put( "empresa_nome", session.getAttribute( sessionCompanyName ) ); + hmValues.put( "empresa_id", session.getAttribute( sessionEmpresaId ) ); + hmValues.put( "estabelecimento_id", session.getAttribute( sessionEstabelecimentoId ) ); + hmValues.put( "userRole", userRole ); + hmValues.put( "userName", user ); + //out.println( mergeTemplate( hmValues, super.authenticatedUserTemplate)); + + //out.println( mergeTemplate( user, userRole, super.authenticatedUserTemplate)); + } + else + { + out.println( mergeTemplate( msgErroAuthFail, super.errorTemplate) ); + } + } + + } + catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( msgErroBd , super.errorTemplate) ); + } + catch ( IllegalStateException e ) // session timeout + { + e.printStackTrace(); + out.println( mergeTemplate(msgSessionTimeout, super.errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( msgGenericError , super.errorTemplate) ); + } + } + +} diff --git a/trunk/web/src/WEB-INF/classes/siprp/pagina/siprpServlet.java b/trunk/web/src/WEB-INF/classes/siprp/pagina/siprpServlet.java new file mode 100644 index 00000000..3ca42675 --- /dev/null +++ b/trunk/web/src/WEB-INF/classes/siprp/pagina/siprpServlet.java @@ -0,0 +1,648 @@ +package siprp.pagina; + +import java.io.*; +import java.lang.reflect.Array; +import javax.servlet.*; +import javax.servlet.http.*; +import java.sql.*; +import java.util.*; + +import org.apache.velocity.*; +import org.apache.velocity.app.*; + +import com.evolute.utils.*; +import com.evolute.utils.arrays.*; +import com.evolute.utils.db.*; +import com.evolute.utils.sql.*; +import com.evolute.utils.strings.*; + +public class siprpServlet extends HttpServlet + implements GlobalConstants +{ + // MSG + public static final String msgErroNoUser = "Tem+de+especificar+um+utilizador."; + public static final String msgErroAuthFail = "Utilizador+inexistente+e/ou+Password+errada."; + public static final String msgErroBd = "Erro+na+ligaç&atiolde;o+à+base+de+dados."; + public static final String msgGenericError = "Erro"; + public static final String msgListaEmpresas = "Empresas"; + public static final String msgAcessoNegado = "Acesso+Negado."; + public static final String msgLinkFormatError ="URL+inválido."; + public static final String msgLogin = "Login"; + public static final String msgNovaPasswordErrada="Erro+ao+criar+a+nova+password,+nova+password+inválida."; + public static final String msgButtonNotSuported = "funcionalidade+ainda+não+suportada."; + public static final String msgSessionTimeout = "Por+razões+de+segurança+o+tempo+da+sua+sessão+expirou
" + + "Por+favor+efectue+novamente+o+seu+login.
"; + + // Templates - Nomes e valores + //public static final String loginTemplate = "login.html"; + + public static final String indexTemplate = "index.html"; + public static final String authenticatedUserTemplate = "user.html"; + public static final String authenticatedUserPrintTemplate = "user_print.html"; + public static final String errorTemplate = "frame_erro.html"; + public static final String innerErrorTemplate = "erro.html"; + + public static final String mainTemplate = "main.html"; + //public static final String criticalErrorTemplate = "critical.html"; + public static final String templateVector1 ="v1"; + public static final String templateVector2 ="v2"; + public static final String templateVector3 ="v3"; + public static final String templateUserRole ="userRole"; + public static final String msgTemplate ="msg"; + public static final String templateQuery ="query"; + public static final String buttonPressedTemplate ="buttonPressed"; + + // Query Strings , usadas para na template do velocity saber o que mostar + public static final String queryStringErro = "erro"; + public static final String queryStringEmpresas = "empresas"; + public static final String queryStringEstabelecimentos="estabelecimentos"; + public static final String queryStringTrabalhadores ="trabalhadores"; + public static final String queryStringTrabalhador ="trabalhador"; + + //Botoes, saber qual o botao escholido, campo value dos forms + public static final String botaoLogin = "Entrar"; + public static final String botaoMarcarProximoExame = "Marcar Exame"; + + // Var da Session + public static final String sessionUser="user"; + public static final String sessionUserRole="userRole"; + public static final String sessionPassword="password"; + public static final String sessionEmpresaId="empresaId"; + public static final String sessionEstabelecimentoId="estabelecimentoId"; + public static final String sessionTrabalhadorId="trabalhadorId"; + public static final String sessionCompanyName = "sessionCompanyName"; + public static final String sessionCompanyEmail = "sessionCompanyEmail"; + public static final int sessionTimeout = 3600; // segundos + + public static final String servletName="siprpWeb"; + public static final String superUserRole="manager"; + +// // BD +// public static final String bdHost = "127.0.0.1"; +// public static final String bdPort = "5436"; +// public static final String bdUsername = "siprp"; +// public static final String bdPassword = ""; +// public static final String bdDriver = "org.postgresql.Driver"; +// public static final String bdUrl = "jdbc:postgresql://" + bdHost + ":" + bdPort + "/siprp"; + + public static final String bdEmpresaIdRef = "id"; // campo que contem id da empresa + public static final String bdEmpresaNomeRef = "designacao_social"; // campo que contem nome da empresa + public static final String bdEstIdRef = "id"; // campo que contem nome do estabelecimento + public static final String bdEstNomeRef = "nome"; // campo que contem nome do estabelecimento + public static final String bdTrabIdRef = "id"; // campo que contem id do trabalhador + public static final String bdTrabNomeRef = "nome"; // campo que contem nome do trabalhador + public static final String bdNullString = ""; // String a mostrar quando o campo lido da BD é null + public static final String bdEmailEmpresa = "email"; // campo que contem email da empresa + + protected static ServletContext CONTEXT; + + // Arrays + public static final String[][] trabalhadorDescFields = new String [][] + { // nome que o user ve, nome do campo na tabela + {"Nome", "nome"}, + {"Nº", "numero_mecanografico",}, + {"\u00DAltimo Exame", "ultimo_exame"}, + {"Realizado", "realizado"}, + {"Pr\u00F3ximo Exame", "proximo_exame"}, + {"\u00DAltima Consulta", "ultima_consulta"}, + {"Realizada", "realizada"}, + {"Pr\u00F3xima Consulta", "proxima_consulta"} + }; + + public void init() + { + + try { + CONTEXT = this.getServletContext(); + String TEMPLATE_DIR = this.getServletContext().getRealPath( "/" ) + "html/"; +System.out.println( "DIR: " + TEMPLATE_DIR ); + Properties props = new Properties(); + props.setProperty( "file.resource.loader.path", TEMPLATE_DIR ); + Velocity.init( props ); + Class.forName(bdDriver); + } + catch( Exception e ) + { + e.printStackTrace(); + } + } + + public void doGet( HttpServletRequest req, HttpServletResponse res ) + throws IOException + { + String queryString = req.getQueryString(); + String backUri = req.getRequestURI(); + ServletOutputStream out = res.getOutputStream(); + res.setContentType( "text/html" ); + try + { +System.out.println( "query: " + queryString ); + HttpSession session = req.getSession(true); + session.setMaxInactiveInterval(sessionTimeout); + + if ( queryString == null ) // Reload, 1º vez, etc ... + { + session.invalidate(); + out.println( mergeTemplate ( msgLogin, indexTemplate ) ) ; + } + else if ( session.isNew() && !( queryString.indexOf(queryStringErro) == 0 ) ) // session timeout + { + session.invalidate(); + out.println( mergeTemplate( msgGenericError , errorTemplate ) ); +// doErro(queryString, out); + } + else if ( queryString.equals(queryStringEmpresas) ) // Listar Empresas + { + new doGetListaEmpresas(req,res); + } + else if ( queryString.indexOf(queryStringErro) == 0 ) // Listar Empresas + { +// System.out.println( "entrou" ); + doErro(queryString, out); + } + else // interpretar query string + { + String empresa = null, estabelecimento=null, trabalhador=null; + String query = null; + int checkInt; + + StringTokenizer sToken = new StringTokenizer(queryString,"/") ; + empresa = sToken.nextToken(); // empresa ID + checkInt = Integer.parseInt(empresa); // check int, NumberFormatException + + if (sToken.hasMoreElements()) + { + estabelecimento = sToken.nextToken(); // estabelecimento ID + checkInt = Integer.parseInt(estabelecimento); // check int, NumberFormatException + if (sToken.hasMoreElements()) + { + trabalhador = sToken.nextToken(); // trabalhador ID + try + { + checkInt = Integer.parseInt(trabalhador); // check int, NumberFormatException + } + catch( NumberFormatException nfex ) + { + query = trabalhador; + if( query.indexOf( "trabalhadores_tudo" ) != 0 && query.indexOf( "trabalhadores_pendentes" ) != 0 && + query.indexOf( "_print" ) == -1 ) + { + throw nfex; + } + } + } + } + + if ( estabelecimento == null ) // empresa query + { + session.setAttribute(sessionEmpresaId, empresa); // update HTTP Session + + new doGetListaEstabelecimentos(req,res); + + //out.println( mergeTemplate ( empresa, loginTemplate ) ) ; + } + else if ( trabalhador == null || query != null ) // estabelecimento query + { + session.setAttribute(sessionEmpresaId, empresa); // update HTTP Session + session.setAttribute(sessionEstabelecimentoId, estabelecimento); + + new doGetListaTrabalhadores(req,res, query); + + //out.println( mergeTemplate ( " chama oGetListaTrabalhadores", loginTemplate ) ) ; + } + else // trabalhador query + { + session.setAttribute(sessionEmpresaId, empresa); // update HTTP Session + session.setAttribute(sessionEstabelecimentoId, estabelecimento); + session.setAttribute(sessionTrabalhadorId, trabalhador); + + new doGetTrabalhador(req,res); + + //out.println( mergeTemplate ( trabalhador, loginTemplate ) ) ; + } + } + } + catch ( NumberFormatException e ) // argumentos invalidos + { + e.printStackTrace(); + out.println( mergeTemplate( msgLinkFormatError, backUri, errorTemplate) ); + } + catch ( IllegalStateException e ) // session timeout + { + e.printStackTrace(); + out.println( mergeTemplate(msgSessionTimeout, errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); +// out.println( mergeTemplate( msgGenericError , backUri, errorTemplate ) ); + out.println( mergeTemplate( msgGenericError , errorTemplate ) ); + } +// System.out.println( "fim - " + queryString + " bu " + backUri ); + } + + public void doPost(HttpServletRequest req, HttpServletResponse res) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + //StringBuffer dbQuery; + //ResultSet2DArray rs; + //Connection con = null ; + //Statement stmt = null ; + //String user, userRole, password; + String buttonPressed = req.getParameter("form"); + + try + { + if ( buttonPressed.equals(botaoLogin)) + { + new doPostLogin(req,res); + } + else + { + out.println( mergeTemplate( msgButtonNotSuported, errorTemplate) ); + } + } + /*catch ( SQLException e ) + { + e.printStackTrace(); + out.println( mergeTemplate( msgErroBd , criticalErrorTemplate) ); + }*/ + catch ( IllegalStateException e ) // session timeout + { + e.printStackTrace(); + out.println( mergeTemplate(msgSessionTimeout, errorTemplate) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + out.println( mergeTemplate( msgGenericError , errorTemplate) ); + } + } + + + public String mergeTemplate( HashMap values, String template ) + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + for( Iterator i = values.keySet().iterator(); i.hasNext(); ) + { + String key = ( String ) i.next(); + context.put ( key, values.get( key ) ) ; + } + + Velocity.mergeTemplate(template, Velocity.ENCODING_DEFAULT, context, output ); + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + + + public String mergeTemplate (String msg, String template ) // #1 + { + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + context.put ( msgTemplate , msg ) ; + Velocity.mergeTemplate(template, Velocity.ENCODING_DEFAULT, context, output ); + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public String mergeTemplate (String msg, String userRole, String template ) // #1 + { + + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + context.put ( msgTemplate , msg ) ; + context.put ( templateUserRole, userRole); + Velocity.mergeTemplate(template, Velocity.ENCODING_DEFAULT, context, output ); + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public String mergeTemplate ( String msg, String userRole, String querySelected, Vector vector1, Vector vector2, Vector vector3, String template ) // #2 + { + + VelocityContext context = new VelocityContext(); + StringWriter output = new StringWriter(); + + try + { + context.put ( msgTemplate , msg ) ; + context.put ( templateUserRole, userRole); + context.put ( templateQuery, querySelected ); + context.put ( templateVector1,vector1); + context.put ( templateVector2,vector2); + context.put ( templateVector3,vector3); + Velocity.mergeTemplate(template, Velocity.ENCODING_DEFAULT, context, output ); + return output.toString(); + } + catch( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public void destroy() + { + } + + public void handleSessionTimeout(HttpServletResponse res, String template) + throws IOException + { + ServletOutputStream out = res.getOutputStream(); + try + { + out.println( mergeTemplate( msgSessionTimeout, template) ); + } + catch ( Exception e ) + { + e.printStackTrace(); + + } + } + + public boolean verificaEstabelecimento(Connection con, java.lang.String empresaId, java.lang.String estabelecimentoId) + // verifica se o establecimento pertence à empresa + { + //Connection con = null ; + Statement stmt = null ; + Virtual2DArray rs; + String query; + try + { + //con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword ); + query = "SELECT empresa_id FROM estabelecimentos where id='"+estabelecimentoId+"'"; + if( con != null ) + { + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + } + else + { + rs = getExecuter().executeQuery( new Select( query ) ); + } + String temp=""+rs.get(0,0); // converter de int para String + if( con != null ) + { + stmt.close(); + } + if ( empresaId.equals(temp) ) // estabelecimento pertence à empresa + { + return true; + } + else + { + return false; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return false; + } + + public boolean verificaTrabalhador(Connection con, java.lang.String estabelecimentoId, java.lang.String trabalhadorId) + // verifica se o trabalhador pertence ao estabelecimento + { + //Connection con = null ; + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery; + try + { + //con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword ); + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT estabelecimento_id FROM trabalhadores where id='"+trabalhadorId+"'"); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + String temp=""+rs.get(0,0); // converter de int para String + stmt.close(); + if ( estabelecimentoId.equals(temp) ) // estabelecimento pertence à empresa + { + return true; + } + else + { + return false; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return false; + } + + public void closeSqlCon(Connection con) + { + try + { + if (con != null ) con.close(); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + + } + + public String emailEmpresa(Connection con, String empresaId) + { + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery; + String returnString; + + try + { + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT email FROM empresas, contactos " + + "WHERE empresas.id ='"+empresaId+"' AND empresas.contacto_1 = contactos.id"); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + if( rs.columnLength() > 0 ) + { + returnString = (String)rs.get(0,0); + stmt.close(); + return returnString; + } + else + { + return null; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public String nomeEmpresa(Connection con, String empresaId) + { + Statement stmt = null ; + Virtual2DArray rs; + String returnString; + + try + { + String query = "SELECT designacao_social FROM empresas WHERE id ='"+empresaId+"'"; + if( con != null ) + { + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + } + else + { + rs = getExecuter().executeQuery( new Select( query ) ); + } + if( rs.columnLength() > 0 ) + { + returnString = (String)rs.get(0,0); + if( con != null ) + { + stmt.close(); + } + return returnString; + } + else + { + return null; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public String nomeEstabelecimento(Connection con, java.lang.String estabelecimentoId) + { + Statement stmt = null ; + Virtual2DArray rs; + StringBuffer dbQuery; + String returnString; + + try + { + String query = "SELECT nome FROM estabelecimentos WHERE id ='"+estabelecimentoId+"'"; + if( con != null ) + { + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( query ) ); + } + else + { + rs = getExecuter().executeQuery( new Select( query ) ); + } + if( rs.columnLength() > 0 ) + { + returnString = (String)rs.get(0,0); + if( con != null ) + { + stmt.close(); + } + return returnString; + } + else + { + return null; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public String nomeTrabalhador(Connection con, java.lang.String trabalhadorId) + { + Statement stmt = null ; + ResultSet2DArray rs; + StringBuffer dbQuery; + String returnString; + + try + { + dbQuery = new StringBuffer(); + dbQuery.append( "SELECT nome FROM trabalhadores where id='"+trabalhadorId+"'"); + stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = new ResultSet2DArray( stmt.executeQuery( dbQuery.toString()) ); + if( rs.columnLength() > 0 ) + { + returnString = (String)rs.get(0,0); + stmt.close(); + return returnString; + } + else + { + return null; + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + return null; + } + + public void doErro( String queryString, ServletOutputStream out ) + throws Exception + { + String split[] = queryString.split( "=" ); + String err; + if( split.length > 1 ) + { + err = split[ 1 ]; + } + else + { + err = "Erro"; + } + err = err.replace( '+', ' ' ); + out.println( mergeTemplate( err, innerErrorTemplate) ); + } + + protected Executer getExecuter() + throws Exception + { + ServletContext context = CONTEXT; + DBManager dbm = ( DBManager ) context.getAttribute( Singleton.DEFAULT_DBMANAGER ); + if( dbm == null ) + { + dbm = new JDBCManager( bdLocalUrl, bdLocalUsername, bdLocalPassword , 500, 499, 1, null ); + context.setAttribute( Singleton.DEFAULT_DBMANAGER, dbm ); + } + return dbm.getSharedExecuter(); + } +} + diff --git a/trunk/web/src/WEB-INF/web.xml b/trunk/web/src/WEB-INF/web.xml new file mode 100644 index 00000000..bc00f63f --- /dev/null +++ b/trunk/web/src/WEB-INF/web.xml @@ -0,0 +1,46 @@ + + + + + + SIPRP WEB + SIPRP WEB + + SIPRP WEB + siprp.pagina.siprpServlet + + + SIPRP WEB + /index.html + + + + Request + siprp.pagina.RequestServlet + + + Request + /request + + + + Schedule + siprp.pagina.ScheduleServlet + + + Schedule + /schedule + + + + Relatorio + siprp.pagina.RelatorioServlet + + + Relatorio + /relatorio + + + diff --git a/trunk/web/src/html/clientes.html b/trunk/web/src/html/clientes.html new file mode 100644 index 00000000..75220e84 --- /dev/null +++ b/trunk/web/src/html/clientes.html @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + +
   os +nossos clientes
+ + + + + + + + + + +

+

+
em +desenvolvimento...
+

+

+
+

+
+ + diff --git a/trunk/web/src/html/colaboradores.html b/trunk/web/src/html/colaboradores.html new file mode 100644 index 00000000..4c8488de --- /dev/null +++ b/trunk/web/src/html/colaboradores.html @@ -0,0 +1,50 @@ + + + + + SIPRP - Colaboradores + + + + + + + + + + + + + + + +
   colaboradores
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/contactos.html b/trunk/web/src/html/contactos.html new file mode 100644 index 00000000..ccd32346 --- /dev/null +++ b/trunk/web/src/html/contactos.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Apresentação + + + + + + + + + + + + + + + +
   +contactos
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/conteudos/colaboradores_text.html b/trunk/web/src/html/conteudos/colaboradores_text.html new file mode 100644 index 00000000..97bc3572 --- /dev/null +++ b/trunk/web/src/html/conteudos/colaboradores_text.html @@ -0,0 +1,111 @@ + + + + + + SIPRP - Apresentação + + +Área reservada a colaboradores da SIPRP.
+Esta página dá acesso a funcionalidades exclusivas e confidenciais.
+ + + diff --git a/trunk/web/src/html/conteudos/contactos_text.html b/trunk/web/src/html/conteudos/contactos_text.html new file mode 100644 index 00000000..49d25e25 --- /dev/null +++ b/trunk/web/src/html/conteudos/contactos_text.html @@ -0,0 +1,105 @@ + + + + + SIPRP - Apresentação + + + + +SIPRP – Sociedade Ibérica de Prevenção de Riscos +Profissionais
+
+Edifício Atrium Saldanha
+Praça Duque de Saldanha, 1 – +9º G
+1050 – 094 Lisboa
+
+Telefone: 21 350 45 40
+Fax: 21 350 45 49
+E-mail: geral@siprp.pt
+
+
+Pedir mais informações
+
+ + + + diff --git a/trunk/web/src/html/conteudos/higiene_foto_equip_BA.html b/trunk/web/src/html/conteudos/higiene_foto_equip_BA.html new file mode 100644 index 00000000..27998fee --- /dev/null +++ b/trunk/web/src/html/conteudos/higiene_foto_equip_BA.html @@ -0,0 +1,29 @@ + + + + + SIPRP - Serviços + + + + + + + + + + + + + + +

+
Bomba de Amostragem de ar
+
voltar +»
+
+
+ + diff --git a/trunk/web/src/html/conteudos/higiene_text.html b/trunk/web/src/html/conteudos/higiene_text.html new file mode 100644 index 00000000..26d9268a --- /dev/null +++ b/trunk/web/src/html/conteudos/higiene_text.html @@ -0,0 +1,59 @@ + + + + + SIPRP - Serviços + + +Para a prestação deste serviço, a SIPRP +colocará à disposição um dos seus +Técnicos Superiores de Higiene e Segurança, que +garantirá o cumprimento das seguintes actividades nas +várias instalações da empresa espalhadas por todo +o país:
+

+ - Identificação e avaliação dos +riscos;
+ - Planeamento da prevenção, integrando-a a todos os +níveis da hierarquia;
+ - Elaboração de um programa de +prevenção de riscos profissionais;
+ - Informação sobre riscos e medidas de +protecção;
+ - Organização de medidas a adoptar em caso de +perigo +grave;
+ - Coordenação das auditorias internas para controlo +da aplicação das medidas a implementar;
+  +- Análise dos acidentes de trabalho e doenças +profissionais;
+  +- Recolha e organização de elementos +estatísticos.
+

+Estas actividades estão englobadas nas várias auditorias, +medições, avaliações e respectivos +relatórios efectuados pelo técnico.
+A SIPRP efectuará, no mínimo, DUAS auditorias por cada +estabelecimento e ano, que originarão os respectivos +relatórios técnicos com o levantamento das +condições verificadas e as recomendações +para a resolução das não conformidades encontradas.
+Com esse relatório será elaborado um Plano de +Actuação que será entregue ao coordenador do +serviço na empresa com as acções a desenvolver, +prazos de implementação e responsabilidades.
+Para além dos serviços incluídos e exigidos pela +legislação, a SIPRP possui capacidade (técnica e +humana) para efectuar avaliações específicas no +âmbito da Higiene e Segurança.
+Desde Estudos de Ruído, Iluminação, Conforto +Térmico, Qualidade do Ar, bem como outros factores relacionados +com outros riscos físicos, químicos ou biológicos.
+Para o cumprimento destes requisitos a SIPRP possui equipamento +técnico próprio, de acordo com as normas nacionais e +internacionais.
+ + diff --git a/trunk/web/src/html/conteudos/higiene_text_equip.html b/trunk/web/src/html/conteudos/higiene_text_equip.html new file mode 100644 index 00000000..a972d096 --- /dev/null +++ b/trunk/web/src/html/conteudos/higiene_text_equip.html @@ -0,0 +1,36 @@ + + + + + SIPRP - Serviços + + +Bombas de Amostragem
+ - Para captação do volume de ar pretendido para a +amostra
+Reguladores de Caudal
+ - Para regulação do caudal de ar pretendido para +amostra
+Monitores de Conforto +Térmico
+ - Para determinação dos parâmetros de +conforto térmico
+Termoanemómetros
+ - Para medição da temperatura, humidade relativa e +velocidade do ar
+Explosivímetros
+ - Para medir a concentração de oxigénio, +CO2, Metano, entre outros
+Luxímetros
+ - Para medição de luminância e +iluminância
+Dosímetros
+ - Para avaliação da exposição pessoal +diária de um trabalhador ao ruído
+Sonómetros +Integradores
+ - Para avaliação dos níveis de ruído +ocupacional ou ambiental
+Outros
+ + diff --git a/trunk/web/src/html/conteudos/links_text.html b/trunk/web/src/html/conteudos/links_text.html new file mode 100644 index 00000000..6b7c268d --- /dev/null +++ b/trunk/web/src/html/conteudos/links_text.html @@ -0,0 +1,104 @@ + + + + + SIPRP - Apresentação + + +

Agência Europeia para a +Segurança +e Saúde do Trabalho – www.agency.osha.eu.int
+American +Institute of Chemical Engineers – www.aiche.org
+American +Industrial Hygiene Association – www.aiha.org
+Associação +Portuguesa de Seguradores – www.apseguradores.pt
+Bureau +of Labour Statistics – www.stats.bls.gov
+Chemical +Abstracts Service – www.info.cas.org
+Cornell +University Ergonomics Web – www.ergo.human.cornell.edu
+Direcção +Geral de Estudos Estatística e Planeamento – +www.deep.msst.gov.pt
+Direcção +Geral de Saúde – www.dgsaude.pt
+Factor +Segurança – www.factor-segur.pt
+Grupo +PREMESER – www.premeser.com
+IDICT +- www.idict.gov.pt
+Industrial +Safety and Health News – www.ishn.com
+Institut +Nacional de Recherche et de Securité – www.inrs.fr
+Institute +for Research in Construction – +www.irc.nrc-cnrc.gc.ca/irccontents.html
+Institute +of Occupational Safety Engineering – +www.turva.me.tut.fi/english/indexeng.html
+Instituto +de Apoio às Pequenas e Médias Empresas e ao +Investimento – www.iapmei.pt
+Instituto +Nacional de Estatística – www.ine.pt
+Instituto +para a Qualidade na Formação – +www.inofor.pt
+International +Labor Organization – www.ilo.org
+International +Organization for Standardization – ISO – +www.iso.org/iso/en/isoonline.frontpage
+International +Society for Respiratory Protection – www.isrp.com.au
+International +Commision on Non-Ionozing Radiation Protection – +www.icirp.de
+Ministério +da Segurança Social e do Trabalho – www.msst.gov.pt
+Mutua +Universal – www.muniversal.net
+National +Electrical Safety Foundation – www.nesf.org
+National +Fire Protection Association – www.nfpa.org
+Occupational +Safety and Health Administration – OSHA – www.osha.gov
+Ordem +dos Enfermeiros – www.ordemenfermeiros.pt
+Ordem +dos Médicos – www.ordemdosmedicos.pt
+PREVLER +Online – www.vol.com.br/prevler
+Revista +Proteção – www.protecao.com.br
+Revista +Segurança – www.revistaseguranca.com
+World +Health Organization (OMS) – www.who.int/en

+ + diff --git a/trunk/web/src/html/conteudos/medicina_text.html b/trunk/web/src/html/conteudos/medicina_text.html new file mode 100644 index 00000000..cdbeef47 --- /dev/null +++ b/trunk/web/src/html/conteudos/medicina_text.html @@ -0,0 +1,32 @@ + + + + + SIPRP - Serviços + + +A SIPRP possui um gabinete médico completamente equipado na sua +sede do Atrium Saldanha, em Lisboa, onde se encontra a sua Directora +Clínica, especialista em Medicina do Trabalho.
+Para além disso, e uma vez que tem a possibilidade de prestar o +serviço em todo o território nacional, possui uma rede de +clínicas, médicos, enfermeiros e laboratórios de +análises clínicas contratados com capacidade de poder +prestar o serviço dentro dos parâmetros de qualidade que +preconiza.
+Por último, tem, também, capacidade para fazer deslocar +Médicos do Trabalho às empresas, desde que estas possuam +gabinete médico próprio com as condições +mínimas exigidas pela legislação portuguesa.
+A Direcção Clínica da SIPRP desenha perfis +médicos adequados aos riscos a que estão expostos os +trabalhadores das suas empresas Clientes, não excluindo, +inclusivamente, a possibilidade de serem efectuados outros exames +complementares de diagnóstico conforme os riscos +específicos de cada actividade, como sejam os trabalhadores +expostos a factores físicos (como ruído, stress +térmico, iluminação, entre outros), +químicos (por exemplo, pessoal de limpeza) ou biológicos +(por exemplo, manipuladores de alimentos).
+ + diff --git a/trunk/web/src/html/conteudos/politica_text.html b/trunk/web/src/html/conteudos/politica_text.html new file mode 100644 index 00000000..3e52de72 --- /dev/null +++ b/trunk/web/src/html/conteudos/politica_text.html @@ -0,0 +1,69 @@ + + + + + SIPRP - Serviços + + + +Porque sabemos que a gestão administrativa do serviço de +SHST é difícil para a empresa, a SIPRP tomará a +seu cargo essas tarefas, simplificando todo o processo.
+Notificações ao ISHST(ex-IDICT) (Mod. 1360)
+ +Relatório Anual de Actividade de SHST
+ +Marcações de Consultas
+ +Informação on line
+ +Informação sobre legislação
+ +Controlos de Qualidade
+ + + diff --git a/trunk/web/src/html/conteudos/politica_text_20050106.html b/trunk/web/src/html/conteudos/politica_text_20050106.html new file mode 100644 index 00000000..cc78d7ab --- /dev/null +++ b/trunk/web/src/html/conteudos/politica_text_20050106.html @@ -0,0 +1,59 @@ + + + + + SIPRP - Serviços + + +Porque sabemos que a gestão administrativa do serviço de +SHST é difícil para a empresa, a SIPRP tomará a +seu cargo essas tarefas, simplificando todo o processo.
+Notificações ao ISHST +(ex-IDICT) (Mod. 1360)
+Elaboração e entrega da Notificação em cada +delegação ou subdelegação do ISHST +(ex-IDICT) onde a empresa tenha estabelecimento. Após a +confirmação da recepção desses documentos +por parte do ISHST, serão enviadas cópias autenticadas +para a empresa.
+Relatório Anual de Actividade +de SHST
+Compilação da informação, +elaboração e entrega dos Relatórios (um por cada +estabelecimento) através de suporte informático pela +Internet. Após a confirmação da +recepção desses documentos por parte dos serviços +competentes, serão enviadas cópias para a empresa.
+Marcações de Consultas
+A SIPRP, através do seu avançado sistema +informático, será responsável pela +marcação dos exames de Medicina do Trabalho +(Admissão, Periódico ou Ocasional) conforme a +periodicidade indicada pela legislação (anualmente para +os trabalhadores com menos de 18 e mais de 50 anos e de dois em dois +anos para os restantes).
+Informação on line
+A SIPRP possibilita à empresa, através deste site, a +visualização do histórico do serviço +(consultas efectuadas, marcações, faltas, data da +próxima consulta, se tem Ficha de Aptidão emitida, entre +outros) durante as 24 horas do dia, todos os dias do ano. Essa +informação será, logicamente, confidencial, +não tendo qualquer dado médico (ao abrigo do sigilo +profissional) e exigirá a introdução de uma +palavra passe previamente remetida à empresa.
+Informação sobre +legislação
+A SIPRP será responsável pelo envio, com periodicidade +acordada, da actualização de toda a +legislação de SHST (portuguesa e europeia) sobre a +actividade específica da empresa Cliente, mantendo-a a par de +todas as obrigações legais inerentes.
+Controlos de Qualidade
+Serão efectuados questionários de controlo de qualidade, +por amostragem, tanto aos funcionários da empresas bem como aos +responsáveis directos pelo serviço, com o objectivo de se +poder aperfeiçoar, melhorar ou intervir rapidamente nalgum +aspecto que não corresponda às expectativas da empresa.
+ + diff --git a/trunk/web/src/html/conteudos/servicos_compl_text.html b/trunk/web/src/html/conteudos/servicos_compl_text.html new file mode 100644 index 00000000..ce16c605 --- /dev/null +++ b/trunk/web/src/html/conteudos/servicos_compl_text.html @@ -0,0 +1,71 @@ + + + + + SIPRP - Serviços + + + +A SIPRP, devido à sua competência técnica e humana, +põe à disposição dos seus Clientes um leque +de serviços muito abrangente, tendo sempre em conta o respeito +pela legislação vigente e pelos princípios de +rigor, transparência e qualidade.
+
+Poderá consultar, seguidamente, alguns dos serviços que +poderemos oferecer:
+
+
+Segurança, Higiene e Saúde do Trabalho
+ +Formação
+ +Ergonomia
+ +Estudos e Análises Técnicas de Agentes Físicos (Iluminação, Ruído, Radiações, Ambiente Térmico e Vibrações)
+ +Estudos e Análises Técnicas de Contaminantes Químicos (Poeiras, Gases e Vapores, Líquidos e Fumos)
+ +Estudos e Análises Técnicas de Contaminantes Biológicos (Vírus, Bactérias, Fungos e Parasitas)
+ +Outros
+ +
+ + diff --git a/trunk/web/src/html/conteudos/servicos_compl_text_20050106.html b/trunk/web/src/html/conteudos/servicos_compl_text_20050106.html new file mode 100644 index 00000000..94ebe148 --- /dev/null +++ b/trunk/web/src/html/conteudos/servicos_compl_text_20050106.html @@ -0,0 +1,71 @@ + + + + + SIPRP - Serviços + + +A SIPRP, devido à sua competência técnica e humana, +põe à disposição dos seus Clientes um leque +de serviços muito abrangente, tendo sempre em conta o respeito +pela legislação vigente e pelos princípios de +rigor, transparência e qualidade.
+
+Poderá consultar, seguidamente, alguns dos serviços que +poderemos oferecer:
+
+

+Segurança, Higiene e Saúde do Trabalho
+ - Serviços à Medida do Cliente ou sua actividade +obedecendo à legislação portuguesa em vigor
+ - Medicina do Trabalho
+ - Levantamento e Avaliação de Riscos
+ - Apoio Administrativo
+Formação
+ - Primeiros Socorros
+ - Acções de Sensibilização em Higiene +e +Segurança e EPI’s
+ - Meios de Combate a Incêndios
+ - Movimentação Mecânica de Cargas +(Empilhadores +e outros)
+ - Manipulação de Cargas
+Ergonomia
+ - Avaliação da Carga Física
+ - Movimentação Manual de Cargas
+ - Prevenção de Lesões +Músculo-Esqueléticas
+ - Análise de Postos de Trabalho
+Estudos e Análises Técnicas de Agentes Físicos +(Iluminação, Ruído, Radiações, +Ambiente Térmico e Vibrações)
+ - Estudos de Luminância e Iluminância
+ - Estudos de Ruído Ocupacional
+ - Estudos de Radiações Ionizantes (i.e. RX) e +Não Ionizantes (i.e. Campos Electromagnéticos dos +Computadores)
+ - Estudos de Conforto e Stress Térmico
+ - Estudos de Vibrações
+Estudos e Análises Técnicas de Contaminantes +Químicos (Poeiras, Gases e Vapores, Líquidos e Fumos)
+ - Estudos de Poeiras (Totais e Respiráveis)
+ - Compostos Orgânicos Voláteis, Formaldaído e +Nicotina
+Estudos e Análises Técnicas de Contaminantes +Biológicos (Vírus, Bactérias, Fungos e Parasitas)
+ - Legionella Pneumóphila
+ - Exames Microbiológicos (i.e. interior de condutas do +sistema AVAC)
+ - Estudos de Microrganismos em Suspensão no Ar
+ Outros
+ - Planos de Emergência / Evacuação
+ - Medicina Curativa
+ - Enfermagem
+ - Análises Clínicas
+ - Exames Complementares de Diagnóstico
+ - Comercialização de Sinalética de +Segurança
+

+ + diff --git a/trunk/web/src/html/conteudos/siprp_text.html b/trunk/web/src/html/conteudos/siprp_text.html new file mode 100644 index 00000000..7315af20 --- /dev/null +++ b/trunk/web/src/html/conteudos/siprp_text.html @@ -0,0 +1,28 @@ + + + + + SIPRP - Apresentação + + +A SIPRP - Sociedade Ibérica de Prevenção de Riscos +Profissionais é uma empresa de origem espanhola pertencente ao +Grupo Premeser (www.premeser.com). Este Grupo foi formado com a +finalidade de optimizar as sinergias entre empresas de sectores e +âmbitos geográficos diferentes, resultando num grupo +sólido e competitivo, capaz de oferecer as respostas adequadas +para uma gestão eficaz dos serviços de Segurança, +Higiene e Saúde do Trabalho (SHST) junto dos seus Clientes.
+
+A SIPRP aposta fortemente na inovação +e pretende ser uma +empresa de referência no sector, assentando a sua +actuação no rigor, seriedade e em compromissos +sólidos com os seus Clientes e suas necessidades.
+
+Porque a prevenção é a base de todo o trabalho +nesta área, na SIPRP temos em conta a especificidade da +actividade de cada empresa, as condições de trabalho dos +seus colaboradores e todos os factores que os rodeiam.
+ + diff --git a/trunk/web/src/html/conteudos/siprp_text_inovacao.html b/trunk/web/src/html/conteudos/siprp_text_inovacao.html new file mode 100644 index 00000000..a04576ab --- /dev/null +++ b/trunk/web/src/html/conteudos/siprp_text_inovacao.html @@ -0,0 +1,22 @@ + + + + + SIPRP - Apresentação + + +Como factores de sucesso na inovação, salientamos:
+
+- Atendimento personalizado, baseado numa sólida plataforma +informática;
+- Informação actualizada on-line;
+- Equipamento técnico de última geração;
+- Instalações modernas e funcionais;
+- Técnicos Superiores qualificados;
+- Acompanhamento permanente das necessidades e exigências dos +Clientes;
+- Diversas opções para prestação dos +serviços (à medida de cada actividade)
+
+ + diff --git a/trunk/web/src/html/css/funcs.js b/trunk/web/src/html/css/funcs.js new file mode 100644 index 00000000..099f6df4 --- /dev/null +++ b/trunk/web/src/html/css/funcs.js @@ -0,0 +1,64 @@ +function showhide( id ) +{ + if( document.getElementById ) + { + obj = document.getElementById( id ); + if ( obj.style.display == "none" ) + { + obj.style.display = ""; + document.getElementById( 'span_' + id ).style.color = "#C13F45"; + } + else + { + obj.style.display = "none"; + document.getElementById( 'span_' + id ).style.color = "#497895"; + } + } +} + +function isValidDate( year, month, day ) +{ + return day > 0 && ( day <= [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][ month ] || + day == 29 && month == 2 && year % 4 == 0 && ( year % 100 > 0 || year % 400 == 0 ) ); +} + +function isValid( element, type ) +{ + switch( type ) + { + // date + case 0: + if( element.value.search( /^\d\d?\/\d\d?\/\d{1,4}$/ ) != 0 ) + { + alert( "Formato da data incorrecto." ); + window.setTimeout( "document.getElementById( '" + element.name + "').focus()", 1 ); + return false; + } + date_value = element.value.split( "/" ); + if( ! isValidDate( date_value[ 2 ], date_value[ 1 ], date_value[ 0 ] ) ) + { + alert( "Data inválida." ); + window.setTimeout( "document.getElementById( '" + element.name + "').focus()", 1 ); + return false; + } + break; + // integer + case 1: + if( element.value.search( /^\d\d:\d\d$/ ) != 0 ) + { + alert( "Formato da hora incorrecto." ); + window.setTimeout( "document.getElementById( '" + element.name + "' ).focus()", 1 ); + return false; + } + time_value = element.value.split( ":" ); + if( time_value[ 0 ] > 23 || time_value[ 1 ] > 59 ) + { + alert( "Hora inválida." ); + window.setTimeout( "document.getElementById( '" + element.name + "').focus()", 1 ); + return false; + } + break; + } + + return true; +} diff --git a/trunk/web/src/html/css/style.css b/trunk/web/src/html/css/style.css new file mode 100644 index 00000000..78159917 --- /dev/null +++ b/trunk/web/src/html/css/style.css @@ -0,0 +1,129 @@ +body +{ + color: #497895; + font-family: verdana; + margin-top: 0px; +} + +.text +{ + color: #497895; + font-family: verdana; + font-size: 10pt; + text-align: justify; +} + +.noticias +{ + color: #497895; + font-family: verdana; + font-size: 9pt; + text-align: left; +} + +td.asd +{ + border-width: 1px 1px 1px 1px; + border-style: solid; +} + +td.title +{ + color: #ffffff; + font-family: verdana; + font-size: 10pt; + font-weight: bold; +} + +td.noticias +{ + font-size: 9pt; +} + +td.footer +{ + color: #ffffff; + font-family: verdana; + font-size: 8pt; + text-align: right; +} + +a:link, +a:visited, +a:active +{ + color: #497895; + font-family: verdana; + font-size: 10pt; + font-weight: bold; + text-decoration: none; +} + +a:hover +{ + color: #C13F45; + font-family: verdana; + font-size: 10pt; + font-weight: bold; + text-decoration: none; +} + +a.menu:link, +a.menu:visited, +a.menu:active +{ + color: #FFFFFF; + font-family: verdana; + font-size: 10pt; + font-weight: bold; + text-decoration: none; +} + +a.menu:hover +{ + color: #C13F45; + font-family: verdana; + font-size: 10pt; + font-weight: bold; + text-decoration: none; +} + +a.big:link, +a.big:visited, +a.big:active +{ + color: #497895; + font-family: verdana; + font-size: 12pt; + font-weight: bold; + text-decoration: none; +} + +a.big:hover +{ + color: #C13F45; + font-family: verdana; + font-size: 12pt; + font-weight: bold; + text-decoration: none; +} + +a.copy:link, +a.copy:visited, +a.copy:active +{ + color: #FFFFFF; + font-family: verdana; + font-size: 8pt; + font-weight: normal; + text-decoration: underline; +} + +select, +option, +input +{ + color: #497895; + font-family: verdana; + margin-top: 0px; +} diff --git a/trunk/web/src/html/erro.html b/trunk/web/src/html/erro.html new file mode 100644 index 00000000..ce6f9d47 --- /dev/null +++ b/trunk/web/src/html/erro.html @@ -0,0 +1,44 @@ + + + + + SIPRP - Erro + + + + + + + + + + + + + + + +
  erro
+
+ + + + + + + + + + +

+

+
+ $msg +
+

+
+

+
+ + diff --git a/trunk/web/src/html/frame_erro.html b/trunk/web/src/html/frame_erro.html new file mode 100644 index 00000000..f97eab0b --- /dev/null +++ b/trunk/web/src/html/frame_erro.html @@ -0,0 +1,254 @@ + + + + + + SIPRP + + + + + + + + + + + +

+
+ + + + + + + + + + + + + + + +

+

+
a SIPRPserviçoscolaboradorescontactoslinks 
+ + + + + + + + + + + + + + + + +
+ + +
+
+ + + + + + +
+
+ + + + + + + + + + + + + + + +
user
password
+
+
+

+
+ + + + + + + + + + + + + + +
   notícias
+
+ + + + + + + + + + +

+

+
A SIPRP apresenta o +seu novo site em www.siprp.pt.
+
+Além de conteúdos sobre a empresa e o grupo, é +disponibilizado um portal online com funcionalidades para os seus +clientes.

+

+
+

+
+
+
+ + diff --git a/trunk/web/src/html/higiene.html b/trunk/web/src/html/higiene.html new file mode 100644 index 00000000..1ef5315b --- /dev/null +++ b/trunk/web/src/html/higiene.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Higiene + + + + + + + + + + + + + + + +
   +higiene e segurança
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/index.html b/trunk/web/src/html/index.html new file mode 100644 index 00000000..32d07d04 --- /dev/null +++ b/trunk/web/src/html/index.html @@ -0,0 +1,229 @@ + + + + + + + SIPRP + + + + + + + + + + + +

+
+ + + + + + + + + + + + + + + +

+

+
a SIPRPserviçoscolaboradorescontactoslinks 
+ + + + + + + + + + + + + + +

+
+ + + + + + +
+
+ + + + + + + + + + + + + + + +
user
password
+
+
+
+ + + + + + + + + + + + + +
   notícias
+
+ + + + + + + + + + +

+

+
+ +
+

+
+

+
+
+
+ + diff --git a/trunk/web/src/html/links.html b/trunk/web/src/html/links.html new file mode 100644 index 00000000..ae2134b2 --- /dev/null +++ b/trunk/web/src/html/links.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Links + + + + + + + + + + + + + + + +
   +links úteis
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/mail/cv_enviado.html b/trunk/web/src/html/mail/cv_enviado.html new file mode 100644 index 00000000..0bd37216 --- /dev/null +++ b/trunk/web/src/html/mail/cv_enviado.html @@ -0,0 +1,11 @@ + + + + + + Enviado + + + A sua informação foi enviada com sucesso. + + diff --git a/trunk/web/src/html/mail/cv_nao_enviado.html b/trunk/web/src/html/mail/cv_nao_enviado.html new file mode 100644 index 00000000..dd8c1671 --- /dev/null +++ b/trunk/web/src/html/mail/cv_nao_enviado.html @@ -0,0 +1,12 @@ + + + + + + Erro a enviar + + + Erro a enviar a sua informação.
+ Verifique que preencheu "Nome Completo", "Telefone" e "E-Mail" com um valor válido. + + diff --git a/trunk/web/src/html/mail/envio_cv.txt b/trunk/web/src/html/mail/envio_cv.txt new file mode 100644 index 00000000..69a3da74 --- /dev/null +++ b/trunk/web/src/html/mail/envio_cv.txt @@ -0,0 +1,7 @@ +Envio de CV + +Função: $rec_funcao +Nome: $rec_nome +Morada: $rec_morada +Telefone: $rec_telefone +E-mail: $rec_email diff --git a/trunk/web/src/html/mail/pedido_enviado.html b/trunk/web/src/html/mail/pedido_enviado.html new file mode 100644 index 00000000..ec1854c9 --- /dev/null +++ b/trunk/web/src/html/mail/pedido_enviado.html @@ -0,0 +1,11 @@ + + + + + + Enviado + + + O seu pedido foi enviado com sucesso + + diff --git a/trunk/web/src/html/mail/pedido_informacao.txt b/trunk/web/src/html/mail/pedido_informacao.txt new file mode 100644 index 00000000..3178db98 --- /dev/null +++ b/trunk/web/src/html/mail/pedido_informacao.txt @@ -0,0 +1,5 @@ +Pedido de informação de: +Nome: $request_name +Telefone: $request_phone +E-mail: $request_email +Assunto: $request_details diff --git a/trunk/web/src/html/mail/pedido_nao_enviado.html b/trunk/web/src/html/mail/pedido_nao_enviado.html new file mode 100644 index 00000000..4dcb63f4 --- /dev/null +++ b/trunk/web/src/html/mail/pedido_nao_enviado.html @@ -0,0 +1,11 @@ + + + + + + Erro a enviar + + + Erro a enviar o seu pedido + + diff --git a/trunk/web/src/html/marcacao/CalendarPopup.js b/trunk/web/src/html/marcacao/CalendarPopup.js new file mode 100644 index 00000000..03f4daa3 --- /dev/null +++ b/trunk/web/src/html/marcacao/CalendarPopup.js @@ -0,0 +1,1462 @@ +// =================================================================== +// Author: Matt Kruse +// WWW: http://www.mattkruse.com/ +// +// NOTICE: You may use this code for any purpose, commercial or +// private, without any further permission from the author. You may +// remove this notice from your final code if you wish, however it is +// appreciated by the author if at least my web site address is kept. +// +// You may *NOT* re-distribute this code in any way except through its +// use. That means, you can include it in your product, or your web +// site, or any other form where the code is actually being used. You +// may not put the plain javascript up on your site for download or +// include it in your javascript libraries for download. +// If you wish to share this code with others, please just point them +// to the URL instead. +// Please DO NOT link directly to my .js files from your site. Copy +// the files to your server and use them there. Thank you. +// =================================================================== + + +/* SOURCE FILE: AnchorPosition.js */ + +/* +AnchorPosition.js +Author: Matt Kruse +Last modified: 10/11/02 + +DESCRIPTION: These functions find the position of an tag in a document, +so other elements can be positioned relative to it. + +COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small +positioning errors - usually with Window positioning - occur on the +Macintosh platform. + +FUNCTIONS: +getAnchorPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor. Position is relative to the PAGE. + +getAnchorWindowPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor, relative to the WHOLE SCREEN. + +NOTES: + +1) For popping up separate browser windows, use getAnchorWindowPosition. + Otherwise, use getAnchorPosition + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. +*/ + +// getAnchorPosition(anchorname) +// This function returns an object having .x and .y properties which are the coordinates +// of the named anchor, relative to the page. +function getAnchorPosition(anchorname) { + // This function will return an Object with x and y properties + var useWindow=false; + var coordinates=new Object(); + var x=0,y=0; + // Browser capability sniffing + var use_gebi=false, use_css=false, use_layers=false; + if (document.getElementById) { use_gebi=true; } + else if (document.all) { use_css=true; } + else if (document.layers) { use_layers=true; } + // Logic to find position + if (use_gebi && document.all) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_gebi) { + var o=document.getElementById(anchorname); + x=AnchorPosition_getPageOffsetLeft(o); + y=AnchorPosition_getPageOffsetTop(o); + } + else if (use_css) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_layers) { + var found=0; + for (var i=0; i9?"":"0")+x} + +// ------------------------------------------------------------------ +// isDate ( date_string, format_string ) +// Returns true if date string matches format of format string and +// is a valid date. Else returns false. +// It is recommended that you trim whitespace around the value before +// passing it to this function, as whitespace is NOT ignored! +// ------------------------------------------------------------------ +function isDate(val,format) { + var date=getDateFromFormat(val,format); + if (date==0) { return false; } + return true; + } + +// ------------------------------------------------------------------- +// compareDates(date1,date1format,date2,date2format) +// Compare two date strings to see which is greater. +// Returns: +// 1 if date1 is greater than date2 +// 0 if date2 is greater than date1 of if they are the same +// -1 if either of the dates is in an invalid format +// ------------------------------------------------------------------- +function compareDates(date1,dateformat1,date2,dateformat2) { + var d1=getDateFromFormat(date1,dateformat1); + var d2=getDateFromFormat(date2,dateformat2); + if (d1==0 || d2==0) { + return -1; + } + else if (d1 > d2) { + return 1; + } + return 0; + } + +// ------------------------------------------------------------------ +// formatDate (date_object, format) +// Returns a date in the output format specified. +// The format string uses the same abbreviations as in getDateFromFormat() +// ------------------------------------------------------------------ +function formatDate(date,format) { + format=format+""; + var result=""; + var i_format=0; + var c=""; + var token=""; + var y=date.getYear()+""; + var M=date.getMonth()+1; + var d=date.getDate(); + var E=date.getDay(); + var H=date.getHours(); + var m=date.getMinutes(); + var s=date.getSeconds(); + var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; + // Convert real date parts into formatted versions + var value=new Object(); + if (y.length < 4) {y=""+(y-0+1900);} + value["y"]=""+y; + value["yyyy"]=y; + value["yy"]=y.substring(2,4); + value["M"]=M; + value["MM"]=LZ(M); + value["MMM"]=MONTH_NAMES[M-1]; + value["NNN"]=MONTH_NAMES[M+11]; + value["d"]=d; + value["dd"]=LZ(d); + value["E"]=DAY_NAMES[E+7]; + value["EE"]=DAY_NAMES[E]; + value["H"]=H; + value["HH"]=LZ(H); + if (H==0){value["h"]=12;} + else if (H>12){value["h"]=H-12;} + else {value["h"]=H;} + value["hh"]=LZ(value["h"]); + if (H>11){value["K"]=H-12;} else {value["K"]=H;} + value["k"]=H+1; + value["KK"]=LZ(value["K"]); + value["kk"]=LZ(value["k"]); + if (H > 11) { value["a"]="PM"; } + else { value["a"]="AM"; } + value["m"]=m; + value["mm"]=LZ(m); + value["s"]=s; + value["ss"]=LZ(s); + while (i_format < format.length) { + c=format.charAt(i_format); + token=""; + while ((format.charAt(i_format)==c) && (i_format < format.length)) { + token += format.charAt(i_format++); + } + if (value[token] != null) { result=result + value[token]; } + else { result=result + token; } + } + return result; + } + +// ------------------------------------------------------------------ +// Utility functions for parsing in getDateFromFormat() +// ------------------------------------------------------------------ +function _isInteger(val) { + var digits="1234567890"; + for (var i=0; i < val.length; i++) { + if (digits.indexOf(val.charAt(i))==-1) { return false; } + } + return true; + } +function _getInt(str,i,minlength,maxlength) { + for (var x=maxlength; x>=minlength; x--) { + var token=str.substring(i,i+x); + if (token.length < minlength) { return null; } + if (_isInteger(token)) { return token; } + } + return null; + } + +// ------------------------------------------------------------------ +// getDateFromFormat( date_string , format_string ) +// +// This function takes a date string and a format string. It matches +// If the date string matches the format string, it returns the +// getTime() of the date. If it does not match, it returns 0. +// ------------------------------------------------------------------ +function getDateFromFormat(val,format) { + val=val+""; + format=format+""; + var i_val=0; + var i_format=0; + var c=""; + var token=""; + var token2=""; + var x,y; + var now=new Date(); + var year=now.getYear(); + var month=now.getMonth()+1; + var date=1; + var hh=now.getHours(); + var mm=now.getMinutes(); + var ss=now.getSeconds(); + var ampm=""; + + while (i_format < format.length) { + // Get next token from format string + c=format.charAt(i_format); + token=""; + while ((format.charAt(i_format)==c) && (i_format < format.length)) { + token += format.charAt(i_format++); + } + // Extract contents of value based on format token + if (token=="yyyy" || token=="yy" || token=="y") { + if (token=="yyyy") { x=4;y=4; } + if (token=="yy") { x=2;y=2; } + if (token=="y") { x=2;y=4; } + year=_getInt(val,i_val,x,y); + if (year==null) { return 0; } + i_val += year.length; + if (year.length==2) { + if (year > 70) { year=1900+(year-0); } + else { year=2000+(year-0); } + } + } + else if (token=="MMM"||token=="NNN"){ + month=0; + for (var i=0; i11)) { + month=i+1; + if (month>12) { month -= 12; } + i_val += month_name.length; + break; + } + } + } + if ((month < 1)||(month>12)){return 0;} + } + else if (token=="EE"||token=="E"){ + for (var i=0; i12)){return 0;} + i_val+=month.length;} + else if (token=="dd"||token=="d") { + date=_getInt(val,i_val,token.length,2); + if(date==null||(date<1)||(date>31)){return 0;} + i_val+=date.length;} + else if (token=="hh"||token=="h") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<1)||(hh>12)){return 0;} + i_val+=hh.length;} + else if (token=="HH"||token=="H") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<0)||(hh>23)){return 0;} + i_val+=hh.length;} + else if (token=="KK"||token=="K") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<0)||(hh>11)){return 0;} + i_val+=hh.length;} + else if (token=="kk"||token=="k") { + hh=_getInt(val,i_val,token.length,2); + if(hh==null||(hh<1)||(hh>24)){return 0;} + i_val+=hh.length;hh--;} + else if (token=="mm"||token=="m") { + mm=_getInt(val,i_val,token.length,2); + if(mm==null||(mm<0)||(mm>59)){return 0;} + i_val+=mm.length;} + else if (token=="ss"||token=="s") { + ss=_getInt(val,i_val,token.length,2); + if(ss==null||(ss<0)||(ss>59)){return 0;} + i_val+=ss.length;} + else if (token=="a") { + if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";} + else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";} + else {return 0;} + i_val+=2;} + else { + if (val.substring(i_val,i_val+token.length)!=token) {return 0;} + else {i_val+=token.length;} + } + } + // If there are any trailing characters left in the value, it doesn't match + if (i_val != val.length) { return 0; } + // Is date valid for month? + if (month==2) { + // Check for leap year + if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year + if (date > 29){ return 0; } + } + else { if (date > 28) { return 0; } } + } + if ((month==4)||(month==6)||(month==9)||(month==11)) { + if (date > 30) { return 0; } + } + // Correct hours value + if (hh<12 && ampm=="PM") { hh=hh-0+12; } + else if (hh>11 && ampm=="AM") { hh-=12; } + var newdate=new Date(year,month-1,date,hh,mm,ss); + return newdate.getTime(); + } + +// ------------------------------------------------------------------ +// parseDate( date_string [, prefer_euro_format] ) +// +// This function takes a date string and tries to match it to a +// number of possible date formats to get the value. It will try to +// match against the following international formats, in this order: +// y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d +// M/d/y M-d-y M.d.y MMM-d M/d M-d +// d/M/y d-M-y d.M.y d-MMM d/M d-M +// A second argument may be passed to instruct the method to search +// for formats like d/M/y (european format) before M/d/y (American). +// Returns a Date object or null if no patterns match. +// ------------------------------------------------------------------ +function parseDate(val) { + var preferEuro=(arguments.length==2)?arguments[1]:false; + generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); + monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); + dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); + var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst'); + var d=null; + for (var i=0; i tags may cause errors. + +USAGE: +// Create an object for a WINDOW popup +var win = new PopupWindow(); + +// Create an object for a DIV window using the DIV named 'mydiv' +var win = new PopupWindow('mydiv'); + +// Set the window to automatically hide itself when the user clicks +// anywhere else on the page except the popup +win.autoHide(); + +// Show the window relative to the anchor name passed in +win.showPopup(anchorname); + +// Hide the popup +win.hidePopup(); + +// Set the size of the popup window (only applies to WINDOW popups +win.setSize(width,height); + +// Populate the contents of the popup window that will be shown. If you +// change the contents while it is displayed, you will need to refresh() +win.populate(string); + +// set the URL of the window, rather than populating its contents +// manually +win.setUrl("http://www.site.com/"); + +// Refresh the contents of the popup +win.refresh(); + +// Specify how many pixels to the right of the anchor the popup will appear +win.offsetX = 50; + +// Specify how many pixels below the anchor the popup will appear +win.offsetY = 100; + +NOTES: +1) Requires the functions in AnchorPosition.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a PopupWindow object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a PopupWindow object or + the autoHide() will not work correctly. +*/ + +// Set the position of the popup window based on the anchor +function PopupWindow_getXYPosition(anchorname) { + var coordinates; + if (this.type == "WINDOW") { + coordinates = getAnchorWindowPosition(anchorname); + } + else { + coordinates = getAnchorPosition(anchorname); + } + this.x = coordinates.x; + this.y = coordinates.y; + } +// Set width/height of DIV/popup window +function PopupWindow_setSize(width,height) { + this.width = width; + this.height = height; + } +// Fill the window with contents +function PopupWindow_populate(contents) { + this.contents = contents; + this.populated = false; + } +// Set the URL to go to +function PopupWindow_setUrl(url) { + this.url = url; + } +// Set the window popup properties +function PopupWindow_setWindowProperties(props) { + this.windowProperties = props; + } +// Refresh the displayed contents of the popup +function PopupWindow_refresh() { + if (this.divName != null) { + // refresh the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).innerHTML = this.contents; + } + else if (this.use_css) { + document.all[this.divName].innerHTML = this.contents; + } + else if (this.use_layers) { + var d = document.layers[this.divName]; + d.document.open(); + d.document.writeln(this.contents); + d.document.close(); + } + } + else { + if (this.popupWindow != null && !this.popupWindow.closed) { + if (this.url!="") { + this.popupWindow.location.href=this.url; + } + else { + this.popupWindow.document.open(); + this.popupWindow.document.writeln(this.contents); + this.popupWindow.document.close(); + } + this.popupWindow.focus(); + } + } + } +// Position and show the popup, relative to an anchor object +function PopupWindow_showPopup(anchorname) { + this.getXYPosition(anchorname); + this.x += this.offsetX; + this.y += this.offsetY; + if (!this.populated && (this.contents != "")) { + this.populated = true; + this.refresh(); + } + if (this.divName != null) { + // Show the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).style.left = this.x + "px"; + document.getElementById(this.divName).style.top = this.y + "px"; + document.getElementById(this.divName).style.visibility = "visible"; + } + else if (this.use_css) { + document.all[this.divName].style.left = this.x; + document.all[this.divName].style.top = this.y; + document.all[this.divName].style.visibility = "visible"; + } + else if (this.use_layers) { + document.layers[this.divName].left = this.x; + document.layers[this.divName].top = this.y; + document.layers[this.divName].visibility = "visible"; + } + } + else { + if (this.popupWindow == null || this.popupWindow.closed) { + // If the popup window will go off-screen, move it so it doesn't + if (this.x<0) { this.x=0; } + if (this.y<0) { this.y=0; } + if (screen && screen.availHeight) { + if ((this.y + this.height) > screen.availHeight) { + this.y = screen.availHeight - this.height; + } + } + if (screen && screen.availWidth) { + if ((this.x + this.width) > screen.availWidth) { + this.x = screen.availWidth - this.width; + } + } + var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); + this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); + } + this.refresh(); + } + } +// Hide the popup +function PopupWindow_hidePopup() { + if (this.divName != null) { + if (this.use_gebi) { + document.getElementById(this.divName).style.visibility = "hidden"; + } + else if (this.use_css) { + document.all[this.divName].style.visibility = "hidden"; + } + else if (this.use_layers) { + document.layers[this.divName].visibility = "hidden"; + } + } + else { + if (this.popupWindow && !this.popupWindow.closed) { + this.popupWindow.close(); + this.popupWindow = null; + } + } + } +// Pass an event and return whether or not it was the popup DIV that was clicked +function PopupWindow_isClicked(e) { + if (this.divName != null) { + if (this.use_layers) { + var clickX = e.pageX; + var clickY = e.pageY; + var t = document.layers[this.divName]; + if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { + return true; + } + else { return false; } + } + else if (document.all) { // Need to hard-code this to trap IE for error-handling + var t = window.event.srcElement; + while (t.parentElement != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentElement; + } + return false; + } + else if (this.use_gebi && e) { + var t = e.originalTarget; + while (t.parentNode != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentNode; + } + return false; + } + return false; + } + return false; + } + +// Check an onMouseDown event to see if we should hide +function PopupWindow_hideIfNotClicked(e) { + if (this.autoHideEnabled && !this.isClicked(e)) { + this.hidePopup(); + } + } +// Call this to make the DIV disable automatically when mouse is clicked outside it +function PopupWindow_autoHide() { + this.autoHideEnabled = true; + } +// This global function checks all PopupWindow objects onmouseup to see if they should be hidden +function PopupWindow_hidePopupWindows(e) { + for (var i=0; i0) { + this.type="DIV"; + this.divName = arguments[0]; + } + else { + this.type="WINDOW"; + } + this.use_gebi = false; + this.use_css = false; + this.use_layers = false; + if (document.getElementById) { this.use_gebi = true; } + else if (document.all) { this.use_css = true; } + else if (document.layers) { this.use_layers = true; } + else { this.type = "WINDOW"; } + this.offsetX = 0; + this.offsetY = 0; + // Method mappings + this.getXYPosition = PopupWindow_getXYPosition; + this.populate = PopupWindow_populate; + this.setUrl = PopupWindow_setUrl; + this.setWindowProperties = PopupWindow_setWindowProperties; + this.refresh = PopupWindow_refresh; + this.showPopup = PopupWindow_showPopup; + this.hidePopup = PopupWindow_hidePopup; + this.setSize = PopupWindow_setSize; + this.isClicked = PopupWindow_isClicked; + this.autoHide = PopupWindow_autoHide; + this.hideIfNotClicked = PopupWindow_hideIfNotClicked; + } + +/* SOURCE FILE: CalendarPopup.js */ + +// HISTORY +// ------------------------------------------------------------------ +// Feb 7, 2005: Fixed a CSS styles to use px unit +// March 29, 2004: Added check in select() method for the form field +// being disabled. If it is, just return and don't do anything. +// March 24, 2004: Fixed bug - when month name and abbreviations were +// changed, date format still used original values. +// January 26, 2004: Added support for drop-down month and year +// navigation (Thanks to Chris Reid for the idea) +// September 22, 2003: Fixed a minor problem in YEAR calendar with +// CSS prefix. +// August 19, 2003: Renamed the function to get styles, and made it +// work correctly without an object reference +// August 18, 2003: Changed showYearNavigation and +// showYearNavigationInput to optionally take an argument of +// true or false +// July 31, 2003: Added text input option for year navigation. +// Added a per-calendar CSS prefix option to optionally use +// different styles for different calendars. +// July 29, 2003: Fixed bug causing the Today link to be clickable +// even though today falls in a disabled date range. +// Changed formatting to use pure CSS, allowing greater control +// over look-and-feel options. +// June 11, 2003: Fixed bug causing the Today link to be unselectable +// under certain cases when some days of week are disabled +// March 14, 2003: Added ability to disable individual dates or date +// ranges, display as light gray and strike-through +// March 14, 2003: Removed dependency on graypixel.gif and instead +/// use table border coloring +// March 12, 2003: Modified showCalendar() function to allow optional +// start-date parameter +// March 11, 2003: Modified select() function to allow optional +// start-date parameter +/* +DESCRIPTION: This object implements a popup calendar to allow the user to +select a date, month, quarter, or year. + +COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small +positioning errors - usually with Window positioning - occur on the +Macintosh platform. +The calendar can be modified to work for any location in the world by +changing which weekday is displayed as the first column, changing the month +names, and changing the column headers for each day. + +USAGE: +// Create a new CalendarPopup object of type WINDOW +var cal = new CalendarPopup(); + +// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv' +var cal = new CalendarPopup('mydiv'); + +// Easy method to link the popup calendar with an input box. +cal.select(inputObject, anchorname, dateFormat); +// Same method, but passing a default date other than the field's current value +cal.select(inputObject, anchorname, dateFormat, '01/02/2000'); +// This is an example call to the popup calendar from a link to populate an +// input box. Note that to use this, date.js must also be included!! +Select + +// Set the type of date select to be used. By default it is 'date'. +cal.setDisplayType(type); + +// When a date, month, quarter, or year is clicked, a function is called and +// passed the details. You must write this function, and tell the calendar +// popup what the function name is. +// Function to be called for 'date' select receives y, m, d +cal.setReturnFunction(functionname); +// Function to be called for 'month' select receives y, m +cal.setReturnMonthFunction(functionname); +// Function to be called for 'quarter' select receives y, q +cal.setReturnQuarterFunction(functionname); +// Function to be called for 'year' select receives y +cal.setReturnYearFunction(functionname); + +// Show the calendar relative to a given anchor +cal.showCalendar(anchorname); + +// Hide the calendar. The calendar is set to autoHide automatically +cal.hideCalendar(); + +// Set the month names to be used. Default are English month names +cal.setMonthNames("January","February","March",...); + +// Set the month abbreviations to be used. Default are English month abbreviations +cal.setMonthAbbreviations("Jan","Feb","Mar",...); + +// Show navigation for changing by the year, not just one month at a time +cal.showYearNavigation(); + +// Show month and year dropdowns, for quicker selection of month of dates +cal.showNavigationDropdowns(); + +// Set the text to be used above each day column. The days start with +// sunday regardless of the value of WeekStartDay +cal.setDayHeaders("S","M","T",...); + +// Set the day for the first column in the calendar grid. By default this +// is Sunday (0) but it may be changed to fit the conventions of other +// countries. +cal.setWeekStartDay(1); // week is Monday - Sunday + +// Set the weekdays which should be disabled in the 'date' select popup. You can +// then allow someone to only select week end dates, or Tuedays, for example +cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week + +// Selectively disable individual days or date ranges. Disabled days will not +// be clickable, and show as strike-through text on current browsers. +// Date format is any format recognized by parseDate() in date.js +// Pass a single date to disable: +cal.addDisabledDates("2003-01-01"); +// Pass null as the first parameter to mean "anything up to and including" the +// passed date: +cal.addDisabledDates(null, "01/02/03"); +// Pass null as the second parameter to mean "including the passed date and +// anything after it: +cal.addDisabledDates("Jan 01, 2003", null); +// Pass two dates to disable all dates inbetween and including the two +cal.addDisabledDates("January 01, 2003", "Dec 31, 2003"); + +// When the 'year' select is displayed, set the number of years back from the +// current year to start listing years. Default is 2. +// This is also used for year drop-down, to decide how many years +/- to display +cal.setYearSelectStartOffset(2); + +// Text for the word "Today" appearing on the calendar +cal.setTodayText("Hoje"); + +// The calendar uses CSS classes for formatting. If you want your calendar to +// have unique styles, you can set the prefix that will be added to all the +// classes in the output. +// For example, normal output may have this: +// Today +// But if you set the prefix like this: +cal.setCssPrefix("Test"); +// The output will then look like: +// Today +// And you can define that style somewhere in your page. + +// When using Year navigation, you can make the year be an input box, so +// the user can manually change it and jump to any year +cal.showYearNavigationInput(); + +// Set the calendar offset to be different than the default. By default it +// will appear just below and to the right of the anchorname. So if you have +// a text box where the date will go and and anchor immediately after the +// text box, the calendar will display immediately under the text box. +cal.offsetX = 20; +cal.offsetY = 20; + +NOTES: +1) Requires the functions in AnchorPosition.js and PopupWindow.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a CalendarPopup object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a CalendarPopup object + or the autoHide() will not work correctly. + +5) The calendar popup display uses style sheets to make it look nice. + +*/ + +// CONSTRUCTOR for the CalendarPopup Object +function CalendarPopup() { + var c; + if (arguments.length>0) { + c = new PopupWindow(arguments[0]); + } + else { + c = new PopupWindow(); + c.setSize(150,175); + } + c.offsetX = -152; + c.offsetY = 25; + c.autoHide(); + // Calendar-specific properties + c.monthNames = new Array("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outobro","Novembro","Dezembro"); + c.monthAbbreviations = new Array("Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"); + c.dayHeaders = new Array("D","S","T","Q","Q","S","S"); + c.returnFunction = "CP_tmpReturnFunction"; + c.returnMonthFunction = "CP_tmpReturnMonthFunction"; + c.returnQuarterFunction = "CP_tmpReturnQuarterFunction"; + c.returnYearFunction = "CP_tmpReturnYearFunction"; + c.weekStartDay = 0; + c.isShowYearNavigation = false; + c.displayType = "date"; + c.disabledWeekDays = new Object(); + c.disabledDatesExpression = ""; + c.yearSelectStartOffset = 2; + c.currentDate = null; + c.todayText="Hoje"; + c.cssPrefix=""; + c.isShowNavigationDropdowns=false; + c.isShowYearNavigationInput=false; + window.CP_calendarObject = null; + window.CP_targetInput = null; + window.CP_dateFormat = "dd/MM/yyyy"; + // Method mappings + c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow; + c.setReturnFunction = CP_setReturnFunction; + c.setReturnMonthFunction = CP_setReturnMonthFunction; + c.setReturnQuarterFunction = CP_setReturnQuarterFunction; + c.setReturnYearFunction = CP_setReturnYearFunction; + c.setMonthNames = CP_setMonthNames; + c.setMonthAbbreviations = CP_setMonthAbbreviations; + c.setDayHeaders = CP_setDayHeaders; + c.setWeekStartDay = CP_setWeekStartDay; + c.setDisplayType = CP_setDisplayType; + c.setDisabledWeekDays = CP_setDisabledWeekDays; + c.addDisabledDates = CP_addDisabledDates; + c.setYearSelectStartOffset = CP_setYearSelectStartOffset; + c.setTodayText = CP_setTodayText; + c.showYearNavigation = CP_showYearNavigation; + c.showCalendar = CP_showCalendar; + c.hideCalendar = CP_hideCalendar; + c.getStyles = getCalendarStyles; + c.refreshCalendar = CP_refreshCalendar; + c.getCalendar = CP_getCalendar; + c.select = CP_select; + c.setCssPrefix = CP_setCssPrefix; + c.showNavigationDropdowns = CP_showNavigationDropdowns; + c.showYearNavigationInput = CP_showYearNavigationInput; + c.copyMonthNamesToWindow(); + // Return the object + return c; + } +function CP_copyMonthNamesToWindow() { + // Copy these values over to the date.js + if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) { + window.MONTH_NAMES = new Array(); + for (var i=0; i\n"; + result += '
\n'; + } + else { + result += '
\n'; + result += '
\n'; + result += '
\n'; + } + // Code for DATE display (default) + // ------------------------------- + if (this.displayType=="date" || this.displayType=="week-end") { + if (this.currentDate==null) { this.currentDate = now; } + if (arguments.length > 0) { var month = arguments[0]; } + else { var month = this.currentDate.getMonth()+1; } + if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { var year = arguments[1]; } + else { var year = this.currentDate.getFullYear(); } + var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31); + if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) { + daysinmonth[2] = 29; + } + var current_month = new Date(year,month-1,1); + var display_year = year; + var display_month = month; + var display_date = 1; + var weekday= current_month.getDay(); + var offset = 0; + + offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ; + if (offset > 0) { + display_month--; + if (display_month < 1) { display_month = 12; display_year--; } + display_date = daysinmonth[display_month]-offset+1; + } + var next_month = month+1; + var next_month_year = year; + if (next_month > 12) { next_month=1; next_month_year++; } + var last_month = month-1; + var last_month_year = year; + if (last_month < 1) { last_month=12; last_month_year--; } + var date_class; + if (this.type!="WINDOW") { + result += ""; + } + result += '\n'; + var refresh = windowref+'CP_refreshCalendar'; + var refreshLink = 'javascript:' + refresh; + if (this.isShowNavigationDropdowns) { + result += ''; + result += ''; + + result += ''; + } + else { + if (this.isShowYearNavigation) { + result += ''; + result += ''; + result += ''; + result += ''; + + result += ''; + if (this.isShowYearNavigationInput) { + result += ''; + } + else { + result += ''; + } + result += ''; + } + else { + result += '\n'; + result += '\n'; + result += '\n'; + } + } + result += '
 <'+this.monthNames[month-1]+'> <'+year+'><<'+this.monthNames[month-1]+' '+year+'>>
\n'; + result += '\n'; + result += '\n'; + for (var j=0; j<7; j++) { + + result += '\n'; + } + result += '\n'; + for (var row=1; row<=6; row++) { + result += '\n'; + for (var col=1; col<=7; col++) { + var disabled=false; + if (this.disabledDatesExpression!="") { + var ds=""+display_year+LZ(display_month)+LZ(display_date); + eval("disabled=("+this.disabledDatesExpression+")"); + } + var dateClass = ""; + if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) { + dateClass = "cpCurrentDate"; + } + else if (display_month == month) { + dateClass = "cpCurrentMonthDate"; + } + else { + dateClass = "cpOtherMonthDate"; + } + if (disabled || this.disabledWeekDays[col-1]) { + result += ' \n'; + } + else { + var selected_date = display_date; + var selected_month = display_month; + var selected_year = display_year; + if (this.displayType=="week-end") { + var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0); + d.setDate(d.getDate() + (7-col)); + selected_year = d.getYear(); + if (selected_year < 1000) { selected_year += 1900; } + selected_month = d.getMonth()+1; + selected_date = d.getDate(); + } + result += ' \n'; + } + display_date++; + if (display_date > daysinmonth[display_month]) { + display_date=1; + display_month++; + } + if (display_month > 12) { + display_month=1; + display_year++; + } + } + result += ''; + } + var current_weekday = now.getDay() - this.weekStartDay; + if (current_weekday < 0) { + current_weekday += 7; + } + result += '\n'; + result += '
'+this.dayHeaders[(this.weekStartDay+j)%7]+'
'+display_date+''+display_date+'
\n'; + if (this.disabledDatesExpression!="") { + var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate()); + eval("disabled=("+this.disabledDatesExpression+")"); + } + if (disabled || this.disabledWeekDays[current_weekday+1]) { + result += ' '+this.todayText+'\n'; + } + else { + result += ' '+this.todayText+'\n'; + } + result += '
\n'; + result += '
\n'; + } + + // Code common for MONTH, QUARTER, YEAR + // ------------------------------------ + if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") { + if (arguments.length > 0) { var year = arguments[0]; } + else { + if (this.displayType=="year") { var year = now.getFullYear()-this.yearSelectStartOffset; } + else { var year = now.getFullYear(); } + } + if (this.displayType!="year" && this.isShowYearNavigation) { + result += ""; + result += '\n'; + result += ' \n'; + result += ' \n'; + result += ' \n'; + result += '
<<'+year+'>>
\n'; + } + } + + // Code for MONTH display + // ---------------------- + if (this.displayType=="month") { + // If POPUP, write entire HTML document + result += '\n'; + for (var i=0; i<4; i++) { + result += ''; + for (var j=0; j<3; j++) { + var monthindex = ((i*3)+j); + result += ''; + } + result += ''; + } + result += '
'+this.monthAbbreviations[monthindex]+'
\n'; + } + + // Code for QUARTER display + // ------------------------ + if (this.displayType=="quarter") { + result += '
\n'; + for (var i=0; i<2; i++) { + result += ''; + for (var j=0; j<2; j++) { + var quarter = ((i*2)+j+1); + result += ''; + } + result += ''; + } + result += '

Q'+quarter+'

\n'; + } + + // Code for YEAR display + // --------------------- + if (this.displayType=="year") { + var yearColumnSize = 4; + result += ""; + result += '\n'; + result += ' \n'; + result += ' \n'; + result += '
<<>>
\n'; + result += '\n'; + for (var i=0; i'+currentyear+''; + } + result += ''; + } + result += '
\n'; + } + // Common + if (this.type == "WINDOW") { + result += "\n"; + } + return result; + } diff --git a/trunk/web/src/html/marcacao/marcacao.html b/trunk/web/src/html/marcacao/marcacao.html new file mode 100644 index 00000000..0418a3c1 --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao.html @@ -0,0 +1,14 @@ + + + + + +Empresa: $empresa
+Estabelecimento: $estabelecimento
+Funcionário: $funcionario
+
+Pedido de marcação de $marcacao_tipo + data(s): $data#if( $marcacao_tipo == 'Consulta' ) + Horário: $hora#end.
+ + diff --git a/trunk/web/src/html/marcacao/marcacao_consulta.html b/trunk/web/src/html/marcacao/marcacao_consulta.html new file mode 100644 index 00000000..96d6b4ea --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_consulta.html @@ -0,0 +1,49 @@ + + + + + Marcação de consulta + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ Marcação de Consulta para:
+ $funcionario +
Data(s)*:
Horário:
+ Nota: a marcação está sujeita a confirmação via email.
+ * - campo de preenchimento obrigatório +
+ +
+
+ + diff --git a/trunk/web/src/html/marcacao/marcacao_enviada.html b/trunk/web/src/html/marcacao/marcacao_enviada.html new file mode 100644 index 00000000..481963aa --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_enviada.html @@ -0,0 +1,11 @@ + + + + + Marcação de consulta / exame + + + + O pedido de marcação foi enviado com sucesso. + + diff --git a/trunk/web/src/html/marcacao/marcacao_exame.html b/trunk/web/src/html/marcacao/marcacao_exame.html new file mode 100644 index 00000000..3bcddc85 --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_exame.html @@ -0,0 +1,43 @@ + + + + + Marcação de exames + + + + + +
+ + + + + + + + + + + + + + +
+ Marcação de Exames para:
+ $funcionario +
Data(s)*:
+ Nota: a marcação está sujeita a confirmação via email.
+ * - campo de preenchimento obrigatório +
+ +
+
+ + diff --git a/trunk/web/src/html/marcacao/marcacao_menu.html b/trunk/web/src/html/marcacao/marcacao_menu.html new file mode 100644 index 00000000..0c605749 --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_menu.html @@ -0,0 +1,62 @@ + + + + + Marcação de consulta / exame + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ Marcação para:
+ $funcionario +
+ Consulta + Exame +
Data:dd/mm/aaaa
Hora:hh:mm
+ Nota: a marcação está sujeita a confirmação via email. +
+ +
+
+ + diff --git a/trunk/web/src/html/marcacao/marcacao_nao_enviada.html b/trunk/web/src/html/marcacao/marcacao_nao_enviada.html new file mode 100644 index 00000000..5621b521 --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_nao_enviada.html @@ -0,0 +1,11 @@ + + + + + Marcação de consulta / exame + + + + Ocorreu um erro a enviar o pedido de marcação. + + diff --git a/trunk/web/src/html/marcacao/marcacao_sessao_expirou.html b/trunk/web/src/html/marcacao/marcacao_sessao_expirou.html new file mode 100644 index 00000000..3a84b5fc --- /dev/null +++ b/trunk/web/src/html/marcacao/marcacao_sessao_expirou.html @@ -0,0 +1,11 @@ + + + + + Sessão expirou + + + + A sua sessão expirou. Para efectuar uma marcação, autentique-se novamente. + + diff --git a/trunk/web/src/html/medicina.html b/trunk/web/src/html/medicina.html new file mode 100644 index 00000000..d52815fb --- /dev/null +++ b/trunk/web/src/html/medicina.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Medicina + + + + + + + + + + + + + + + +
   +medicina do trabalho
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/noticias/mostrar_noticias.html b/trunk/web/src/html/noticias/mostrar_noticias.html new file mode 100644 index 00000000..ddea30a6 --- /dev/null +++ b/trunk/web/src/html/noticias/mostrar_noticias.html @@ -0,0 +1,11 @@ + + + + + Notícias + + + + $noticias + + diff --git a/trunk/web/src/html/politica.html b/trunk/web/src/html/politica.html new file mode 100644 index 00000000..3713c26b --- /dev/null +++ b/trunk/web/src/html/politica.html @@ -0,0 +1,52 @@ + + + + + SIPRP + + + + + + + + + + + + + + + +
   +política de qualidade e apoio administrativo
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/relatorio/pedido.html b/trunk/web/src/html/relatorio/pedido.html new file mode 100644 index 00000000..427733c2 --- /dev/null +++ b/trunk/web/src/html/relatorio/pedido.html @@ -0,0 +1,9 @@ + + + + +Empresa: $empresa
+
+Pedido de envio de relatório do ano: $ano
+ + diff --git a/trunk/web/src/html/relatorio/pedido_enviado.html b/trunk/web/src/html/relatorio/pedido_enviado.html new file mode 100644 index 00000000..9b530aa6 --- /dev/null +++ b/trunk/web/src/html/relatorio/pedido_enviado.html @@ -0,0 +1,11 @@ + + + + + Envio de dados do relatório anual + + + + O pedido foi enviado com sucesso. + + diff --git a/trunk/web/src/html/relatorio/pedido_nao_enviado.html b/trunk/web/src/html/relatorio/pedido_nao_enviado.html new file mode 100644 index 00000000..196da035 --- /dev/null +++ b/trunk/web/src/html/relatorio/pedido_nao_enviado.html @@ -0,0 +1,11 @@ + + + + + Envio de dados do relatório anual + + + + Ocorreu um erro a enviar o pedido. + + diff --git a/trunk/web/src/html/relatorio/pedido_relatorio.html b/trunk/web/src/html/relatorio/pedido_relatorio.html new file mode 100644 index 00000000..5dd5bf9f --- /dev/null +++ b/trunk/web/src/html/relatorio/pedido_relatorio.html @@ -0,0 +1,35 @@ + + + + + Pedido de dados do relatório anual + + + + + +
+ + + + + + + + + + +
+ Pedido de dados do relatório anual +
Ano pretendido:
+ +
+
+ + diff --git a/trunk/web/src/html/relatorio/pedido_sessao_expirou.html b/trunk/web/src/html/relatorio/pedido_sessao_expirou.html new file mode 100644 index 00000000..0311eda3 --- /dev/null +++ b/trunk/web/src/html/relatorio/pedido_sessao_expirou.html @@ -0,0 +1,11 @@ + + + + + Sessão expirou + + + + A sua sessão expirou. Para efectuar o pedido, autentique-se novamente. + + diff --git a/trunk/web/src/html/servicos.html b/trunk/web/src/html/servicos.html new file mode 100644 index 00000000..f4585f4f --- /dev/null +++ b/trunk/web/src/html/servicos.html @@ -0,0 +1,31 @@ + + + + + SIPRP - Serviços + + + + + + + + + + + + +

+
-Serviços +Complementares
+ -Medicina do +Trabalho
+ -Política de +Qualidade e Apoio Administrativo
+ -Higiene e +Segurança
+ + diff --git a/trunk/web/src/html/servicos_compl.html b/trunk/web/src/html/servicos_compl.html new file mode 100644 index 00000000..163977df --- /dev/null +++ b/trunk/web/src/html/servicos_compl.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Serviços + + + + + + + + + + + + + + + +
   +serviços complementares
+
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/siprp.html b/trunk/web/src/html/siprp.html new file mode 100644 index 00000000..37d5babe --- /dev/null +++ b/trunk/web/src/html/siprp.html @@ -0,0 +1,52 @@ + + + + + SIPRP - Apresentação + + + + + + + + + + + + + + + +
   +a +siprp
+ + + + + + + + + + +

+

+

+

+

+
+

+
+ + diff --git a/trunk/web/src/html/user.html b/trunk/web/src/html/user.html new file mode 100644 index 00000000..b3d8a59f --- /dev/null +++ b/trunk/web/src/html/user.html @@ -0,0 +1,396 @@ + + + + + SIPRP + + + + + + + + + + + + + +

+ + + + + + + + + + #if( $userRole != "manager" ) + + + #end + + + +
   $userName    pedido de relatório anual...logout »   
+ + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + #if( $query == "empresas" ) + #set( $listaTitle = "empresas" ) + #elseif( $query == "estabelecimentos" ) + #set( $listaTitle = "estabelecimentos" ) + #elseif( $query == "trabalhadores" || $query == "trabalhadores_tudo" || $query == "trabalhadores_pendentes" ) + #set( $listaTitle = "funcionários:" ) + #set( $lista_funcionarios = 1 ) + #else ##( $query == "trabalhador" ) + #set( $listaTitle = "funcionário" ) + #end + + + #if( $lista_funcionarios ) + + + + #end + + + + + + + + + + + + + + +
   acesso restrito
+ + + + + + + + + + + + + + +
+ #if( $userRole == "manager" && $empresa_nome ) + Empresa: $!empresa_nome + #else + Empresa: $!empresa_nome + #end +
+ #if( $estabelecimento_id ) + Estabelecimento: $!estabelecimento_nome + #else + Estabelecimento: + #end +
+ #if( $query == "trabalhador" ) + Funcionário: $!funcionario.nome  - Data de Nascimento: $!funcionario.data_nascimento + #else + Funcionário: + #end + + #if( $query == "trabalhador" ) + + #end +
+ +
+
+ + + + + + + + +
   funcionários:   todos   com ficha de aptidão   com pendências         imprimir
+ #else +
   $listaTitle
+ #if ($query == "trabalhador") + (*)ECD - Exames Complementares de Diagnóstico

+ + + + + + + + + + + + + + + + + + + + +
Último ECD(*)RealizadoÚltima ConsultaRealizadaResultadoPróximo ECD(*)Próxima Consulta
$!funcionario.ultimo_exame $!funcionario.realizado $!funcionario.ultima_consulta $!funcionario.realizada $!funcionario.resultado $!funcionario.proximo_exame $!funcionario.proxima_consulta 
+ #elseif( $query == "trabalhadores" ) + (*)ECD - Exames Complementares de Diagnóstico

+ + + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + + + #end +
  NomeÚltimo ECD(*)Última consultaPróxima consulta
$dados_trabalhador.Nome $dados_trabalhador.ultimo_exame $dados_trabalhador.ultima_consulta $dados_trabalhador.proxima_consulta 
+ #elseif( $query == "trabalhadores_tudo" ) + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + #end +
  NomeData da Ficha de Aptidão
  $dados_trabalhador.Nome$dados_trabalhador.Data  
+ #elseif( $query == "trabalhadores_pendentes" ) + - pendente    + - marcado    + - tratado
+ (*)ECD - Exames Complementares de Diagnóstico

+ + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + + #end +
  NomeECD(*)Consulta
  $dados_trabalhador.Nome
+ #else + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + $v2.get($counter)
+ #end + #end +
+
+
+ + diff --git a/trunk/web/src/html/user_print.html b/trunk/web/src/html/user_print.html new file mode 100644 index 00000000..821ac555 --- /dev/null +++ b/trunk/web/src/html/user_print.html @@ -0,0 +1,284 @@ + + + + + SIPRP + + + + + + + + + + + +

+ + + + + + +
+ +
+ + + + + + +
+ + + + + + + + + + + + + + + + + + + #if( $query == "trabalhadores" ) + #set( $listaTitle = "Todos os Funcionários" ) + #elseif( $query == "trabalhadores_tudo" ) + #set( $listaTitle = "Funcionários com Tudo Resolvido" ) + #elseif( $query == "trabalhadores_pendentes" ) + #set( $listaTitle = "Funcionários com Pendências" ) + #end + + + + + + + + + + + + +
   
+ + + + + + + + + + +
+ Empresa: $!empresa_nome +
+ Estabelecimento: $!estabelecimento_nome +
+ +
+
   $listaTitle
+ #if( $query == "trabalhadores" ) + (*)ECD - Exames Complementares de Diagnóstico

+ + + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + + + #end +
  NomeÚltimo ECD(*)Última consultaPróxima consulta
$dados_trabalhador.Nome $dados_trabalhador.ultimo_exame $dados_trabalhador.ultima_consulta $dados_trabalhador.proxima_consulta 
+ + #elseif( $query == "trabalhadores_tudo" ) + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + #end +
  NomeData da Ficha de Aptidão
  $dados_trabalhador.Nome$dados_trabalhador.Data  
+ #elseif( $query == "trabalhadores_pendentes" ) + + (*)ECD - Exames Complementares de Diagnóstico

+ + + + + + + #foreach( $element in $v1 ) + #set ( $counter = $velocityCount - 1 ) + #set ( $dados_trabalhador = $v2.get($counter) ) + + + + + + + #end +
  NomeECD(*)Consulta
  $dados_trabalhador.Nome$dados_trabalhador.Exame_estado$dados_trabalhador.Consulta_estado
+ #end +
+
+
+ + diff --git a/trunk/web/src/missing b/trunk/web/src/missing new file mode 100644 index 00000000..efd71a22 --- /dev/null +++ b/trunk/web/src/missing @@ -0,0 +1,4 @@ +/trunk/html/images/ +/trunk/html/html/conteudos/Images/ +/trunk/html/html/images/ +/trunk/html/conteudos/Images/