diff --git a/trunk/SIPRPSoft/.classpath b/trunk/SIPRPSoft/.classpath index 2ac224c0..5f021696 100644 --- a/trunk/SIPRPSoft/.classpath +++ b/trunk/SIPRPSoft/.classpath @@ -29,7 +29,6 @@ - @@ -47,5 +46,6 @@ + diff --git a/trunk/SIPRPSoft/lib/shst.jar b/trunk/SIPRPSoft/lib/shst.jar index a63c41b0..caef5a88 100644 Binary files a/trunk/SIPRPSoft/lib/shst.jar and b/trunk/SIPRPSoft/lib/shst.jar differ diff --git a/trunk/SIPRPSoft/properties/1-development/app.properties b/trunk/SIPRPSoft/properties/1-development/app.properties index e2882b8f..d439ff87 100644 --- a/trunk/SIPRPSoft/properties/1-development/app.properties +++ b/trunk/SIPRPSoft/properties/1-development/app.properties @@ -28,6 +28,8 @@ app.icon.path=logo/icon.png #usado em UserDataProvider (shst.jar) web_aware.default_role = siprpuser +web.images_app_url = http://www.evolute.pt:13080/SIPRPImages/image?id= + lembrete.desmarcou = SIPRP Desmarcou lembrete.notice_exame_days = 15 lembrete.notice_visita_days = -11 \ No newline at end of file diff --git a/trunk/SIPRPSoft/properties/2-testing/app.properties b/trunk/SIPRPSoft/properties/2-testing/app.properties index 5ab92ffd..b253bbae 100644 --- a/trunk/SIPRPSoft/properties/2-testing/app.properties +++ b/trunk/SIPRPSoft/properties/2-testing/app.properties @@ -37,6 +37,8 @@ app.icon.path=logo/icon.png #usado em UserDataProvider (shst.jar) web_aware.default_role = siprpuser +web.images_app_url = http://www.evolute.pt:13080/SIPRPImages/image?id= + lembrete.desmarcou = SIPRP Desmarcou lembrete.notice_exame_days = 15 lembrete.notice_visita_days = -11 diff --git a/trunk/SIPRPSoft/properties/3-production/app.properties b/trunk/SIPRPSoft/properties/3-production/app.properties index b864a0a3..28b4b2d0 100644 --- a/trunk/SIPRPSoft/properties/3-production/app.properties +++ b/trunk/SIPRPSoft/properties/3-production/app.properties @@ -36,6 +36,8 @@ app.icon.path=logo/icon.png #usado em UserDataProvider (shst.jar) web_aware.default_role = siprpuser +web.images_app_url = http://www.evolute.pt:13080/SIPRPImages/image?id= + lembrete.desmarcou = SIPRP Desmarcou lembrete.notice_exame_days = 15 lembrete.notice_visita_days = -11 diff --git a/trunk/SIPRPSoft/properties/4-WebApps/app.properties b/trunk/SIPRPSoft/properties/4-WebApps/app.properties index 966c2f1d..daee042a 100644 --- a/trunk/SIPRPSoft/properties/4-WebApps/app.properties +++ b/trunk/SIPRPSoft/properties/4-WebApps/app.properties @@ -35,6 +35,8 @@ app.icon.path=logo/icon.png #usado em UserDataProvider (shst.jar) web_aware.default_role = siprpuser +web.images_app_url = http://www.evolute.pt:13080/SIPRPImages/image?id= + lembrete.desmarcou = SIPRP Desmarcou lembrete.notice_exame_days = 15 lembrete.notice_visita_days = -11 diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafButton.java b/trunk/SIPRPSoft/src/leaf/ui/LeafButton.java deleted file mode 100644 index 45b947dd..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafButton.java +++ /dev/null @@ -1,78 +0,0 @@ -package leaf.ui; - -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -import javax.swing.ImageIcon; -import javax.swing.JButton; - -public class LeafButton extends JButton -{ - private static final long serialVersionUID = 1L; - - private ImageIcon icon = null; - - public LeafButton(String text) - { - super( text ); - setOpaque( false ); - } - - public LeafButton( ImageIcon icon ) - { - super( icon ); - this.icon = icon; - setOpaque( false ); - } - - protected void paintComponent( Graphics g ) - { - if( icon == null ) - { - boolean pushed = getModel().isPressed(); -// Color borderColor = getBackground(); -// Color highlightColor = getBackground(); - Color textColor = isEnabled() ? getForeground() : getForeground().brighter().brighter().brighter(); - Color textAccent = getBackground(); - Color textAccentHot = getBackground(); - GradientPaint topGradientUp = new GradientPaint( 0, 0, getBackground().brighter(), 0, getHeight() / 2, getBackground() ); - GradientPaint topGradientDown = new GradientPaint( 0, 0, getBackground().brighter(), 0, getHeight() / 2, getBackground() ); - GradientPaint bottomGradientDown = new GradientPaint( 0, getHeight() / 2, getBackground(), 0, getHeight(), getBackground().darker() ); - GradientPaint bottomGradientUp = new GradientPaint( 0, getHeight() / 2, getBackground(), 0, getHeight(), getBackground().darker().darker() ); - Graphics2D g2 = (Graphics2D) g; - g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); - - int height = getHeight() / 2; - - g2.setPaint( pushed ? topGradientDown : topGradientUp ); - g2.fillRect( 0, 0, getWidth(), height ); - - g2.setPaint( pushed ? bottomGradientDown : bottomGradientUp ); - g2.fillRect( 0, height, getWidth(), height ); - - // g2.setColor( borderColor ); - // g2.drawRect( 0, 0, getWidth() - 1, getHeight() - 1 ); - // - // g2.setColor( highlightColor ); - // g2.drawRect( 1, 1, getWidth() - 3, getHeight() - 3 ); - - int x = (getWidth() - g2.getFontMetrics().stringWidth( getText() )) / 2; - int y = getHeight() - ((getHeight() - g2.getFontMetrics().getHeight()) / 2) - 3; - - y += 1; - g2.setColor( pushed ? textAccentHot : textAccent ); - g2.drawString( getText(), x, y ); - - y -= 1; - g2.setColor( textColor ); - g2.drawString( getText(), x, y ); - } - else - { - super.paintComponent( g ); - } - } -} \ No newline at end of file diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafCalendarDialog.java b/trunk/SIPRPSoft/src/leaf/ui/LeafCalendarDialog.java deleted file mode 100644 index d59eab18..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafCalendarDialog.java +++ /dev/null @@ -1,149 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Calendar; -import java.util.Date; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.border.BevelBorder; - -import com.toedter.calendar.JCalendar; - -public class LeafCalendarDialog extends JDialog -{ - private static final long serialVersionUID = 1L; - public static final int ABOVE = 0; - public static final int BELOW = 1; - public static final int RIGHT = 0; - public static final int LEFT = 1; - - private boolean ok = false; - private boolean clear = false; - - private Calendar cal = null; - - private boolean enableClean = true; - - private boolean enableCancel = true; - - - private final JCalendar calendarPanel = new JCalendar( null, null, false, false ); - - /** Creates a new instance of JCalendarDialog */ - public LeafCalendarDialog( LeafWindow parentFrame ) - { - super(parentFrame); - this.enableClean = true; - setModal( true ); - setupComponents(); - setUndecorated( true ); - setLocationRelativeTo( null ); - setVisible( true ); - } - - - public LeafCalendarDialog( LeafWindow parentFrame, JComponent parent, boolean enableClean ) - { - super(parentFrame); - this.enableClean = enableClean; - setModal( true ); - setupComponents(); - setUndecorated( true ); - setLocationRelativeTo( parent ); - setVisible( true ); - } - - public LeafCalendarDialog( LeafWindow parentFrame, boolean enableClean, boolean enableCancel ) - { - super(parentFrame); - this.enableClean = enableClean; - this.enableCancel = enableCancel; - setModal( true ); - setupComponents(); - setUndecorated( true ); - setLocationRelativeTo( null ); - setVisible( true ); - } - - private void setupComponents() - { - TableLayout layout = new TableLayout(new double[]{TableLayout.FILL,TableLayout.FILL,TableLayout.FILL}, new double[]{TableLayout.FILL, TableLayout.MINIMUM}); - - getContentPane().setLayout( layout ); - - getContentPane().add( calendarPanel, new TableLayoutConstraints(0,0,2,0)); - - LeafButton okButton = new LeafButton( "OK" ); - okButton.addActionListener( new ActionListener() - { - public void actionPerformed( ActionEvent e ) - { - ok = true; - close(); - } - } ); - LeafButton cancelarButton = new LeafButton( "Cancelar" ); - cancelarButton.setEnabled( enableCancel ); - cancelarButton.addActionListener( new ActionListener() - { - public void actionPerformed( ActionEvent e ) - { - ok = false; - close(); - } - } ); - - LeafButton limparButton = new LeafButton( "Limpar" ); - limparButton.setEnabled(enableClean); - limparButton.addActionListener( new ActionListener() - { - public void actionPerformed( ActionEvent e ) - { - ok = false; - clear = true; - close(); - } - } ); - - - getContentPane().add( okButton, new TableLayoutConstraints(0,1) ); - getContentPane().add( cancelarButton, new TableLayoutConstraints(1,1) ); - getContentPane().add( limparButton, new TableLayoutConstraints(2,1) ); - - setSize( 250, 250 ); - - ((JComponent) getContentPane()).setBorder( BorderFactory.createBevelBorder( BevelBorder.RAISED ) ); - } - - public Date getDate() - { - Date result = null; - if( ok ) - { - cal = Calendar.getInstance(); - cal.set( Calendar.HOUR_OF_DAY, 12 ); - cal = calendarPanel.getCalendar(); - cal.set( Calendar.YEAR, calendarPanel.getYearChooser().getYear() ); - cal.set( Calendar.DAY_OF_MONTH, calendarPanel.getDayChooser().getDay() ); - result = cal != null ? cal.getTime() : null; - } - else if( clear ) - { - result = new Date( 0 ); - } - return result; - } - - public void close() - { - setVisible( false ); - dispose(); - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafDialog.java b/trunk/SIPRPSoft/src/leaf/ui/LeafDialog.java deleted file mode 100644 index a48f0dbf..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafDialog.java +++ /dev/null @@ -1,39 +0,0 @@ -package leaf.ui; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; - -import javax.swing.JOptionPane; - -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.ui.DialogException; - -public class LeafDialog -{ - - public static void error( Exception e ) - { - if( e != null ) - { - ErrorLogger.logException( e ); - e.printStackTrace( System.out ); - DialogException.showException( e ); - } - } - - public static boolean confirmDelete( boolean masculino, boolean plural, String nome ) - { - return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( - null, - "Tem a certeza que deseja remover " + - ( masculino ? "o" : "a" ) + - ( plural ? "s" : "" ) + - " " + nome + " seleccionad" + - ( masculino ? "o" : "a" ) + - ( plural ? "s" : "" ) + - "?", - "Confirmar remo" + ccedil + atilde + "o", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafGradientPanel.java b/trunk/SIPRPSoft/src/leaf/ui/LeafGradientPanel.java deleted file mode 100644 index 4a26e4a2..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafGradientPanel.java +++ /dev/null @@ -1,29 +0,0 @@ -package leaf.ui; - -import java.awt.Color; - -import javax.swing.JPanel; - -public class LeafGradientPanel extends JPanel -{ - private static final long serialVersionUID = 1L; - - public LeafGradientPanel() - { - setBackground( new Color(220,220,220) ); - } - -// @Override -// public void paintComponent( Graphics g ) -// { -// Graphics2D g2d = (Graphics2D) g; -// GradientPaint gradientIn = new GradientPaint( 0, 0, getBackground(), getWidth()/2, 0, Color.DARK_GRAY ); -// g2d.setPaint( gradientIn ); -// g2d.fillRect( 0, 0, getWidth()/2, getHeight() ); -// -// GradientPaint gradientOut = new GradientPaint( getWidth()/2, 0, Color.DARK_GRAY, getWidth(),0, getBackground() ); -// g2d.setPaint( gradientOut ); -// g2d.fillRect( getWidth()/2, 0, getWidth(), getHeight() ); -// } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafIconButton.java b/trunk/SIPRPSoft/src/leaf/ui/LeafIconButton.java deleted file mode 100644 index baa9a75f..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafIconButton.java +++ /dev/null @@ -1,71 +0,0 @@ -package leaf.ui; - -import java.io.IOException; - -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.images.ImageException; -import com.evolute.utils.images.ImageIconLoader; - -public class LeafIconButton extends LeafButton implements LeafUIConstants -{ - private static final long serialVersionUID = 1L; - - private LeafIconButton( String imagePath ) throws ImageException, IOException - { - super( ImageIconLoader.loadImageIcon( imagePath ) ); - } - - public static LeafIconButton createDefaultNewButton() - { - LeafIconButton result = createButton( ICON_NAME_CREATE ); - result.setToolTipText( "Criar" ); - return result; - } - - public static LeafIconButton createDefaultEditButton() - { - LeafIconButton result = createButton( ICON_NAME_EDIT ); - result.setToolTipText( "Editar" ); - return result; - } - - public static LeafIconButton createDefaultRemoveButton() - { - LeafIconButton result = createButton( ICON_NAME_REMOVE ); - result.setToolTipText( "Remover" ); - return result; - } - - public static LeafIconButton createButton( String imagePath ) - { - LeafIconButton result = null; - if( imagePath != null ) - { - try - { - result = new LeafIconButton( imagePath ); -// result.setMargin( new Insets(0,0,0,0) ); - } - catch( ImageException e ) - { - ErrorLogger.logException( e ); - } - catch ( IOException e ) - { - ErrorLogger.logException( e ); - } - } - return result; - } - - public static LeafIconButton createButton( String title, String imagePath ) - { - LeafIconButton result = createButton( imagePath ); - if( result != null ) - { - result.setText( title ); - } - return result; - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafInputField.java b/trunk/SIPRPSoft/src/leaf/ui/LeafInputField.java deleted file mode 100644 index dc77b29a..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafInputField.java +++ /dev/null @@ -1,631 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.GradientPaint; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; - -import com.evolute.adt.OrderedMap; - - - -public class LeafInputField extends JPanel implements FocusListener, MouseListener, PropertyChangeListener -{ - - public static final String PROPERTY_CHANGED_CONSTANT = "LEAF_INPUT_PROPERTY_CHANGED"; - public static final String PROPERTY_CHANGED_CLICK = "LEAF_PROPERTY_CHANGED_CLICK"; - private static final long serialVersionUID = 1L; - - private static final DateFormat sdf = DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) ); - - private static final int defaultColorDec = 20; - - private int colorDec = defaultColorDec; - - public Dimension size = null; - - private Color hot = null; - private Color cold = null; - private Color background = null; - private Color endColor = null; - private Color highLightColor = new Color( 180, 255, 180 ); - - private Object selectedOption = null; - - private boolean isEditable = false; - - private boolean isClickable = false; - - private boolean highLighted = false; - - private boolean collapseOptions = true; - - private ObjClass object = null; - - private GradientPaint outerContour = null; - private GradientPaint outerReversedContour = null; - private GradientPaint innerContour = null; - private GradientPaint innerReversedContour = null; - private GradientPaint gradient = null; - private TableLayout layout = null; - - private JComponent thiz = null; - - private List theeze = null; - - public LeafInputField() - { - super(); - setOpaque( false ); - setBorder( BorderFactory.createEmptyBorder( 3, 10, 3, 10 ) ); - setBackground( Color.WHITE ); - hot = getBackground(); - cold = new Color( hot.getRed() > colorDec ? hot.getRed() - colorDec : 0, hot.getGreen() > colorDec ? hot.getGreen() - colorDec : 0, hot.getBlue() > colorDec ? hot.getBlue() - colorDec : 0, hot.getAlpha() ); - background = cold; - setObject( null ); - } - - public boolean isCollapseOptions() - { - return collapseOptions; - } - - public void setCollapseOptions( boolean collapse ) - { - collapseOptions = collapse; - } - - private String getStringFromUser() - { - LeafTextDialog textDialog = new LeafTextDialog( getParentWindow(), this, (String) object, true ); - return textDialog.getText(); - } - - private Object getOptionFromUser() - { - if( object instanceof Map ) - { - if(((Map) object).size() > 0) - { - LeafOptionDialog optionDialog = new LeafOptionDialog( getParentWindow(), (Map) object, null ); - return optionDialog.getOption(); - } - } - else if( object instanceof OrderedMap ) - { - if(((OrderedMap) object).rows() > 0) - { - LeafOptionDialog optionDialog = new LeafOptionDialog( getParentWindow(), (OrderedMap) object, null, null, null, null ); - return optionDialog.getOption(); - } - } - return null; - } - - private Date getDateFromUser() - { - LeafCalendarDialog calendarDialog = new LeafCalendarDialog( getParentWindow() ); - return calendarDialog.getDate(); - } - - private LeafWindow getParentWindow() - { - LeafWindow result = null; - for( Container parent = this.getParent(); parent != null; parent = parent.getParent() ) - { - if( parent instanceof LeafWindow ) - { - result = (LeafWindow) parent; - } - } - return result; - } - - protected void paintComponent( Graphics g ) - { - Graphics2D g2d = (Graphics2D) g; - int width = getWidth(), height = getHeight(); - setColors( width, height ); - g2d.setPaint( outerReversedContour ); - g2d.fillRect( 15, 0, width / 4, height ); - g2d.setPaint( outerContour ); - g2d.fillRect( width / 4, 0, width, height ); - g2d.setPaint( innerReversedContour ); - g2d.fillRect( 15, 0, width / 4, height - 1 ); - g2d.setPaint( innerContour ); - g2d.fillRect( width / 4, 0, width, height - 1 ); - g2d.setPaint( gradient ); - g2d.fillRoundRect( 0, 2, width, height - 5, 15, 15 ); - super.paintComponent( g ); - } - - private void setColors( int width, int height ) - { - endColor = getGradientEndColor( background ); - outerContour = new GradientPaint( width / 4, 0, Color.GRAY, width, 0, this.getParent().getBackground() ); - outerReversedContour = new GradientPaint( 15, 0, this.getParent().getBackground(), width / 4, 0, Color.GRAY ); - innerContour = new GradientPaint( width / 4, 0, Color.LIGHT_GRAY, width, 0, this.getParent().getBackground() ); - innerReversedContour = new GradientPaint( 15, 0, this.getParent().getBackground(), width / 4, 0, Color.LIGHT_GRAY ); - gradient = new GradientPaint( 0, 0, background, width, height, endColor ); - } - - private Color getGradientEndColor( Color startColor ) - { - return getParent() != null ? getParent().getBackground() : startColor; - } - - public boolean getSelected() - { - return highLighted; - } - - public void setSelected( boolean selected ) - { - highLighted = selected; - background = selected ? highLightColor : cold; - repaint(); - } - - public void setEditable( boolean editable ) - { - isEditable = editable; - if( !editable ) - { - setMouseOver( false ); - } - setEnabled( editable ); - setObject( object, selectedOption ); - repaint(); - } - - public boolean isEditable() - { - return isEditable; - } - - public void setClickable( boolean clickable ) - { - isClickable = clickable; - if( !clickable ) - { - setMouseOver( false ); - } - repaint(); - } - - public boolean isClickable() - { - return isClickable; - } - - private void setupCollapsedPanel() - { - List values = ((OrderedMap) object).getValues( selectedOption ); - theeze = new ArrayList(); - if( values != null ) - { - double[] rows = new double[] { - TableLayout.MINIMUM - }; - double[] cols = new double[values.size() > 0 ? (values.size() * 2 - 1) : 0]; - for( int i = 0; i < cols.length; ++i ) - { - cols[i] = (i % 2 == 0) ? TableLayout.FILL : TableLayout.MINIMUM; - } - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - thiz.setLayout( layout ); - for( int i = 0, a = 0; i < cols.length; ++i ) - { - JComponent comp = null; - if( i % 2 == 0 ) - { - Object value = values.get( a++ ); - comp = new JLabel( value == null ? " " : value.toString() ); - theeze.add( comp ); - } - else - { - comp = new JSeparator( JSeparator.VERTICAL ); - } - thiz.add( comp, new TableLayoutConstraints( i, 0 ) ); - } - } - } - - private void setupUncollapsedPanel() - { - theeze = new ArrayList(); - OrderedMap map = (OrderedMap) object; - double[] rows = new double[map.rows() > 0 ? (map.rows() * 2 - 1) : 0]; - double[] cols = new double[map.columns() > 0 ? (map.columns() * 2 - 1) : 0]; - for( int i = 0; i < rows.length; ++i ) - { - rows[i] = (i % 2 == 0) ? TableLayout.MINIMUM : TableLayout.MINIMUM; - } - for( int i = 0; i < cols.length; ++i ) - { - cols[i] = (i % 2 == 0) ? TableLayout.FILL : TableLayout.MINIMUM; - } - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - thiz.setLayout( layout ); - - for( int i = 0, a = 0; i < rows.length; ++i ) - { - if( i % 2 == 0 ) - { - List values = map.getRow( a++ ); - for( int j = 0, b = 0; j < cols.length; ++j ) - { - JComponent comp = null; - if( j % 2 == 0 ) - { - Object value = values.get( b++ ); - - LeafInputField leaf; - if( value instanceof LeafInputField ) - { - leaf = (LeafInputField) value; - } - else - { - leaf = new LeafInputField(); - leaf.setObject( value ); - if( j > 1 ) - { - leaf.setEditable( isEditable ); - } - } - - comp = leaf; - theeze.add( comp ); - } - else - { - JSeparator sep = new JSeparator( JSeparator.VERTICAL ); - sep.setForeground( cold ); - comp = sep; - } - thiz.add( comp, new TableLayoutConstraints( j, i ) ); - } - } - else - { - JSeparator sep = new JSeparator(); - sep.setForeground( cold ); - thiz.add( sep, new TableLayoutConstraints( 0, i, cols.length - 1, i ) ); - } - } - } - - private void setSelectedObject( Object key ) - { - selectedOption = key; - if( object != null && thiz != null ) - { - if( object instanceof Map ) - { - Object value = null; - value = ((Map) object).get( selectedOption ); - String text = value == null ? " " : value.toString(); - if( thiz instanceof JTextArea ) - { - ((JTextArea) thiz).setText( text ); - } - else if( thiz instanceof JTextField ) - { - ((JTextField) thiz).setText( text ); - } - else if( thiz instanceof JLabel ) - { - ((JLabel) thiz).setText( text ); - } - } - else if( object instanceof OrderedMap ) - { - if( thiz instanceof JPanel && collapseOptions ) - { - setupCollapsedPanel(); - } - else if( thiz instanceof JPanel && !collapseOptions ) - { - setupUncollapsedPanel(); - } - } - } - } - - public Object getSelectedObject() - { - return selectedOption; - } - - public void setObject( ObjClass object, Object selected ) - { - this.selectedOption = selected; - setObject( object ); - } - - public void setObject( ObjClass object ) - { - this.object = object; - if( object != null ) - { - if( object instanceof Date ) - { - Date date = (Date) object; - String text = date.getTime() == 0 ? "" : sdf.format( object ); - thiz = isEditable ? new JLabel( text ) : new JTextArea( text ); - thiz.setEnabled( false ); - } - else if( object instanceof Map ) - { - thiz = isEditable ? new JLabel( " " ) : new JTextArea( " " ); - setSelectedObject( selectedOption ); - thiz.setEnabled( false ); - } - else if( object instanceof OrderedMap && collapseOptions ) - { - thiz = new JPanel(); - setSelectedObject( selectedOption ); - } - else if( object instanceof OrderedMap && !collapseOptions ) - { - thiz = new JPanel(); - setSelectedObject( selectedOption ); - } - else if( object instanceof LeafInputField ) - { - setObject( (ObjClass) ((LeafInputField) object).getObject(), ((LeafInputField) object).getSelectedObject() ); - } - else if( object instanceof String ) - { - JTextArea textArea = new JTextArea(); - textArea.setEditable( false ); - textArea.setText( object == null ? "" : object.toString() ); - thiz = textArea; - } - else - { - String toString = object.toString(); - if( "".equals( toString ) ) - { - toString = " "; - } - thiz = new JTextArea( toString ); - } - } - else - { - thiz = new JLabel( " " ); - } - reListen(); - reLayout(); - } - - public ObjClass getObject() - { - return this.object; - } - - private void reListen() - { - removeListeners(); - if( theeze != null && !collapseOptions && !theeze.isEmpty() ) - { - for( JComponent current : theeze ) - { - if( current instanceof LeafInputField ) - { - current.addFocusListener( (LeafInputField) current ); - current.addMouseListener( (LeafInputField) current ); - current.addPropertyChangeListener( PROPERTY_CHANGED_CONSTANT, this ); - } - } - } - else - { - thiz.addFocusListener( this ); - thiz.addMouseListener( this ); - } - } - - private void removeListeners() - { - removeListerensFrom( thiz ); - if( theeze != null ) - { - for( JComponent comp : theeze ) - { - removeListerensFrom( comp ); - } - } - } - - private void removeListerensFrom( JComponent comp ) - { - if( comp != null ) - { - FocusListener[] allFocus = thiz.getFocusListeners(); - if( allFocus != null ) - { - for( FocusListener focusListener : allFocus ) - { - comp.removeFocusListener( focusListener ); - } - } - MouseListener[] allMouse = thiz.getMouseListeners(); - if( allMouse != null ) - { - for( MouseListener mouseListener : allMouse ) - { - comp.removeMouseListener( mouseListener ); - } - } - } - } - - private void reLayout() - { - if( thiz != null ) - { - SwingUtilities.invokeLater( new Runnable() - { - @Override - public void run() - { - if( layout == null ) - { - layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.FILL - } ); - LeafInputField.this.setLayout( layout ); - } - else - { - removeAll(); - } - LeafInputField.this.add( thiz, new TableLayoutConstraints( 0, 0 ) ); - revalidate(); - repaint(); - } - } ); - size = thiz.getPreferredSize(); - thiz.setOpaque( false ); - } - } - - @Override - public void focusLost( FocusEvent e ) - { - repaint(); - } - - @Override - public void focusGained( FocusEvent e ) - { - repaint(); - } - - @Override - public void mouseReleased( MouseEvent e ) - { - } - - @Override - public void mousePressed( MouseEvent e ) - { - Object old = null; - if( object != null && isEditable ) - { - if( object instanceof Date ) - { - old = object; - ObjClass newDate = (ObjClass) getDateFromUser(); - if( newDate != null ) - { - setObject( newDate ); - firePropertyChange( PROPERTY_CHANGED_CONSTANT, old, object ); - } - } - else if( object instanceof Map && collapseOptions ) - { - old = selectedOption; - ObjClass out = (ObjClass) getOptionFromUser(); - setObject( object, out ); - firePropertyChange( PROPERTY_CHANGED_CONSTANT, old, selectedOption ); - } - else if( object instanceof OrderedMap && collapseOptions ) - { - old = selectedOption; - ObjClass out = (ObjClass) getOptionFromUser(); - setObject( object, out ); - firePropertyChange( PROPERTY_CHANGED_CONSTANT, old, object ); - } - else if( object instanceof OrderedMap && !collapseOptions ) - { - // old = selectedOption; - // ObjClass out = (ObjClass) getOptionFromUser(); - // setObject( object, out ); - // firePropertyChange( PROPERTY_CHANGED_CONSTANT, old, object ); - } - else if( object instanceof String ) - { - old = object; - setObject( (ObjClass) getStringFromUser() ); - firePropertyChange( PROPERTY_CHANGED_CONSTANT, old, object ); - } - } - if( isClickable ) - { - firePropertyChange( PROPERTY_CHANGED_CLICK, false, true ); - } - // setObject( object, selectedOption ); - } - - @Override - public void mouseExited( MouseEvent e ) - { - setMouseOver( false ); - repaint(); - } - - @Override - public void mouseEntered( MouseEvent e ) - { - setMouseOver( true ); - repaint(); - } - - @Override - public void mouseClicked( MouseEvent e ) - { - } - - private void setMouseOver( boolean mouseOver ) - { - if( mouseOver ) - { - background = (!highLighted && (isEditable || isClickable)) ? hot : background; - } - else - { - background = (!highLighted && (isEditable || isClickable)) ? cold : background; - } - } - - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - firePropertyChange( PROPERTY_CHANGED_CONSTANT, evt.getOldValue(), evt.getNewValue() ); - } -} \ No newline at end of file diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafLogic.java b/trunk/SIPRPSoft/src/leaf/ui/LeafLogic.java deleted file mode 100755 index f41714b6..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafLogic.java +++ /dev/null @@ -1,106 +0,0 @@ -package leaf.ui; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.ArrayList; -import java.util.List; - - -public class LeafLogic -{ - - /** - * Declares an Action - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface Action - { - /** - * true - this action saves data to de database from the components - * false - this action reads from the database to the components - */ - boolean isSave(); - } - - /** - * Binds a UI method with an action - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface LeafUIActionBinding - { - - /** - * The name of the action this method binds to - */ - String [] action(); - } - - /** - * Binds a logic methods with a group of actions - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface LeafLogicActionBinding - { - - /** - * The name of the action this method binds to - */ - String [] actions(); - } - - @Action(isSave = false) - public static final String ACTION_STARTUP = "ACTION_STARTUP"; - - @Action(isSave = false) - public static final String ACTION_REFRESH = "ACTION_REFRESH"; - - @Action(isSave = false) - public static final String ACTION_CANCEL = "ACTION_CANCEL"; - - - private List registeredWindows = new ArrayList(); - - public void addWindow(LeafWindow window) - { - registeredWindows .add(window); - } - - public void runAction( String actionName ) - { - runAction( actionName, null ); - } - - public void runAction( String actionName, Object argument ) - { - for( LeafWindow window : registeredWindows ) - { - window.runAction( actionName, argument ); - } - } - - public void runActionLater( String actionName ) - { - for( LeafWindow window : registeredWindows ) - { - window.runActionLater( actionName ); - } - } - - public void runActionLater( String actionName, Object argument ) - { - for( LeafWindow window : registeredWindows ) - { - window.runActionLater( actionName, argument ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafOptionDialog.java b/trunk/SIPRPSoft/src/leaf/ui/LeafOptionDialog.java deleted file mode 100644 index d78e35f3..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafOptionDialog.java +++ /dev/null @@ -1,300 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.JScrollBar; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.ScrollPaneConstants; - -import siprp.ui.SIPRPFrame; - -import com.evolute.adt.OrderedMap; - - - -public class LeafOptionDialog extends JDialog -{ - private Dimension OPTION_SIZE = new Dimension( 200, 20 ); - private Dimension BUTTON_SIZE = new Dimension( 200, 20 ); - - private int MAX_VISIBLE_OPTIONS = 20; - - private static final long serialVersionUID = 1L; - - private String CANCEL_LABEL = "Cancelar"; - - private String okLabel = null; - - private final JLabel labelMessage = new JLabel(); - - private final JPanel optionsPanel = new JPanel(); - - private final JScrollPane optionsScrollPane = new JScrollPane(); - - private boolean cancelActive = true; - - private LeafInputField submitButton = new LeafInputField(); - - private Map map = null; - - private OrderedMap orderedMap = null; - - private List selected = new ArrayList(); - - private Map mapEnabledForKey = null; - - private Map mapChosenForKey = null; - - private String message = null; - - private boolean ordered = false; - - public LeafOptionDialog( LeafWindow owner, Map map, String message) - { - super( owner ); - this.mapEnabledForKey = new HashMap(); - this.mapChosenForKey = new HashMap(); - this.message = message; - cancelActive = false; - for( KeyClass key : map.keySet() ) - { - mapEnabledForKey.put( key, true ); - } - startup( map, null ); - } - - public LeafOptionDialog( LeafWindow owner, OrderedMap orderedMap, Map chosen, Map enabled, String message, String okButton) - { - super( owner ); - ordered = true; - this.message = message; - okLabel = okButton; - cancelActive = okButton != null; - this.mapChosenForKey = chosen == null ? new HashMap() : chosen; - this.mapEnabledForKey = enabled == null ? new HashMap() : chosen; - if( chosen != null ) - { - for( KeyClass key : chosen.keySet() ) - { - Boolean isChosen = chosen.get( key ); - if( isChosen != null && isChosen ) - { - selected.add( key ); - } - } - } - startup( null, orderedMap ); - } - - private void startup( Map map, OrderedMap orderedMap ) - { - if( map == null ) - { - this.map = new HashMap(); - } - else - { - this.map = map; - } - if( orderedMap == null ) - { - this.orderedMap = new OrderedMap(); - } - else - { - this.orderedMap = orderedMap; - } - setupComponents( map == null ? orderedMap.iterator() : map.keySet().iterator(), map == null ? orderedMap.rows() : map.keySet().size(), map == null ? true : false ); - setUndecorated( true ); - setDefaultCloseOperation( SIPRPFrame.DO_NOTHING_ON_CLOSE ); - getRootPane().setWindowDecorationStyle(JRootPane.NONE); - setSize( getLayout().minimumLayoutSize( getRootPane() ) ); - setLocationRelativeTo( getParent() ); - setModal( true ); - setVisible( true ); - } - - private void setupComponents( Iterator iterator, Integer size, boolean ordered ) - { - double[] cols = new double[] { - TableLayout.PREFERRED - }; - double[] rows = new double[(message == null ? 0 : 2) + 1 + (cancelActive ? 2 : 0)]; - for( int i = 0; i < rows.length; ++i ) - { - rows[i] = TableLayout.PREFERRED; - } - TableLayout layout = new TableLayout( cols, rows ); - layout.setVGap( 3 ); - setContentPane( new LeafGradientPanel() ); - getContentPane().setLayout( layout ); - - int shift = 0; - if( message != null ) - { - labelMessage.setText( message ); - getContentPane().add( labelMessage, new TableLayoutConstraints( 0, shift++ ) ); - getContentPane().add( new JSeparator(), new TableLayoutConstraints( 0, shift++ ) ); - } - setupOptionsComponents( iterator, size ); - getContentPane().add( optionsScrollPane, new TableLayoutConstraints( 0, shift++ ) ); - if( cancelActive ) - { - getContentPane().add( new JSeparator(), new TableLayoutConstraints( 0, shift++ ) ); - submitButton.setObject( ordered ? okLabel : CANCEL_LABEL ); - submitButton.setClickable( true ); - submitButton.setPreferredSize( BUTTON_SIZE ); - getContentPane().add( submitButton, new TableLayoutConstraints( 0, shift++ ) ); - addListenerToComponent( submitButton ); - } - ((JComponent) getContentPane()).setBorder( BorderFactory.createRaisedBevelBorder() ); - } - - private void setupOptionsComponents( Iterator iterator, Integer size ) - { - int maxWidth = OPTION_SIZE.width; - double[] cols = new double[] { - TableLayout.PREFERRED - }; - double[] rows = new double[size]; - for( int i = 0; i < rows.length; ++i ) - { - rows[i] = TableLayout.PREFERRED; - } - TableLayout layout = new TableLayout( cols, rows ); - layout.setVGap( 3 ); - optionsPanel.setLayout( layout ); - KeyClass current = null; - for( int i = 0; i < size && iterator.hasNext(); ++i ) - { - current = iterator.next(); - LeafInputField component = new LeafInputField(); - Object value; - if( ordered ) - { - List values = orderedMap.getValues( current ); - value = (values == null || values.size() == 0) ? null : values.get( 0 ); - } - else - { - value = map.get( current ); - } - component.setObject( value ); - - Boolean isChosen = mapChosenForKey.get( current ); - component.setSelected( isChosen != null && isChosen ); - - Boolean isEnabled = mapEnabledForKey.get( current ); - component.setClickable( isEnabled == null || isEnabled ); - - if(component.size != null && component.size.width > maxWidth ) - { - maxWidth = component.size.width; - } - optionsPanel.add( component, new TableLayoutConstraints( 0, i ) ); - addListenerToComponent( component ); - } - - optionsScrollPane.setViewportView( optionsPanel ); - optionsScrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); - JScrollBar verticalScrollBar = optionsScrollPane.getVerticalScrollBar(); - verticalScrollBar.setUnitIncrement( (int) OPTION_SIZE.getHeight() + 3 ); - optionsScrollPane.setVerticalScrollBar( verticalScrollBar ); - optionsScrollPane.setVerticalScrollBarPolicy( size > MAX_VISIBLE_OPTIONS ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER ); - optionsScrollPane.setPreferredSize( new Dimension( maxWidth + 30 , size > MAX_VISIBLE_OPTIONS ? (MAX_VISIBLE_OPTIONS * ((int) (OPTION_SIZE.getHeight() + 3 )) ) : (size * ((int) (OPTION_SIZE.getHeight() + 3 )) ) )); - } - - private KeyClass getKeyForValue( Object value ) - { - if( value != null && map.containsValue( value ) ) - { - for( KeyClass key : map.keySet() ) - { - if( map.get( key ).equals( value ) ) - { - return key; - } - } - } - else if( ordered ) - { - return orderedMap.getKeyForValue( value ); - } - return null; - } - - private void addListenerToComponent( JComponent component ) - { - component.addPropertyChangeListener( new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent e ) - { - if( e.getSource() instanceof LeafInputField ) - { - LeafInputField source = (LeafInputField) e.getSource(); - if( LeafInputField.PROPERTY_CHANGED_CLICK.equals( e.getPropertyName() ) ) - { - if( !source.equals( submitButton ) ) - { - Object value = source.getObject(); - if( value != null ) - { - KeyClass key = getKeyForValue( value ); - if( selected.contains( key ) ) - { - selected.remove( key ); - source.setSelected( false ); - } - else - { - selected.add( key ); - source.setSelected( true ); - } - } - } - if( okLabel == null || source.equals( submitButton ) ) - { - close(); - } - } - } - } - - } ); - } - - public KeyClass getOption() - { - return selected.isEmpty() ? null : selected.get( 0 ); - } - - public List getSelected() - { - return selected; - } - - public void close() - { - setVisible( false ); - dispose(); - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafRuntimeException.java b/trunk/SIPRPSoft/src/leaf/ui/LeafRuntimeException.java deleted file mode 100644 index c0451e9b..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafRuntimeException.java +++ /dev/null @@ -1,18 +0,0 @@ -package leaf.ui; - -public class LeafRuntimeException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - private boolean abort = false; - - public LeafRuntimeException( boolean all ) - { - this.abort = all; - } - - public boolean isAbort() - { - return abort; - } -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafTableModel.java b/trunk/SIPRPSoft/src/leaf/ui/LeafTableModel.java deleted file mode 100644 index 66d22449..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafTableModel.java +++ /dev/null @@ -1,174 +0,0 @@ -package leaf.ui; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import com.evolute.adt.OrderedMap; -import com.evolute.utils.tables.BaseTableModel; - -public class LeafTableModel extends BaseTableModel -{ - - private static final long serialVersionUID = 1L; - - private OrderedMap map = new OrderedMap(); - - public LeafTableModel(String n[]) - { - super( n, null ); - setChangeable( false ); - } - - public void clearAll() - { - int i = map.rows(); - if( i > 0 ) - { - map.clear(); - fireTableRowsDeleted( 0, i - 1 ); - } - } - - @Override - public int innerGetRowCount() - { - return map == null ? 0 : map.rows(); - } - - @Override - public Object innerGetValueAt( int row, int col ) - { - return map.getValueAt( row, col ); - } - - @Override - public void deleteRow( int row ) - { - map.deleteRow( row ); - } - - public Object getKey( int row ) - { - Object result = null; - if( row < map.rows() ) - { - result = map.getKeyForRow( row ); - } - return result; - } - - public void setValues( Collection v ) - { - Iterator iterator = v.iterator(); - while( iterator.hasNext() ) - { - Object value = iterator.next(); - map.putLast( value, value.toString() ); - } - fireTableDataChanged(); - } - - public void setValues( OrderedMap map ) - { - this.map = (OrderedMap) map; - fireTableDataChanged(); - } - - public void order(int ... colNumber ) - { - if(colNumber != null) - { - map.order(colNumber); - fireTableDataChanged(); - } - } - - @Override - public void appendEmptyRow() - { - map.putLast( map.rows(), (Object) null ); - } - - @Override - public void innerSetValueAt( Object obj, int row, int col ) - { - if( isCellEditable( row, col ) && map.getValueAt( row, col ) != null ) - { - map.setValueAt( row, col, obj ); - } - } - - @Override - public boolean isRowEmpty( int row ) - { - List line = map.getRow( row ); - return line != null && line.size() > 0; - } - - @Override - public boolean innerIsCellEditable( int row, int col ) - { - return false; - } - - public void printContents() - { - for( int r = 0; r < getRowCount(); r++ ) - { - for( int c = 0; c < getColumnCount(); c++ ) - { - Object val = getValueAt( r, c ); - if( val != null ) - { - System.out.print( val.toString() + "\t" ); - } - } - System.out.println( "" ); - } - } - - // public void insertRowAt( Object rowObj, int row ) - // { - // values.add( row, rowObj ); - // fireTableDataChanged(); - // } - // - // public void removeRowAt( int row ) - // { - // values.remove( row ); - // fireTableDataChanged(); - // } - // - // public Object getRowAt( int row ) - // { - // return values.elementAt( row ); - // } - - // public void swapRows( int row1, int row2 ) - // { - // if( row1 == row2 || row1 < 0 || row2 < 0 || row1 >= getRowCount() || row2 - // >= getRowCount() ) - // { - // return; - // } - // // Collections.swap( values, row1, row2 ); - // Object row1Data = getRowAt( row1 ); - // Object row2Data = getRowAt( row2 ); - // if( row1 < row2 ) - // { - // removeRowAt( row2 ); - // removeRowAt( row1 ); - // insertRowAt( row2Data, row1 ); - // insertRowAt( row1Data, row2 ); - // } - // else - // { - // removeRowAt( row1 ); - // removeRowAt( row2 ); - // insertRowAt( row1Data, row2 ); - // insertRowAt( row2Data, row1 ); - // } - // } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafTextAreaEditor.java b/trunk/SIPRPSoft/src/leaf/ui/LeafTextAreaEditor.java deleted file mode 100644 index ed0db935..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafTextAreaEditor.java +++ /dev/null @@ -1,180 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; -import javax.swing.text.JTextComponent; - -import siprp.SIPRPSpellChecker; - -import com.evolute.adt.Validator; -import com.evolute.utils.ui.text.CopyPasteHandler; - - -public class LeafTextAreaEditor extends JPanel -{ - - public static final String ACTION_SAVE = "ACTION_SAVE"; - - public static final String ACTION_REVERT = "ACTION_REVERT"; - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_SAVE = "leaf/ui/icons/save.png"; - - private static final String ICON_NAME_REVERT = "leaf/ui/icons/revert.png"; - - private final LeafButton buttonSave = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private final LeafButton buttonRevert = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final JTextComponent fieldText; - - private final JScrollPane scroll; - - private final Validator validator; - - private String initialValue = ""; - - public LeafTextAreaEditor( Validator validator ) - { - - this( validator, false ); - } - - public LeafTextAreaEditor( Validator validator, boolean textField ) - { - this.validator = validator; - fieldText = textField ? new JTextField() : new JTextArea(); - scroll = new JScrollPane(fieldText); - startupComponents( textField ); - startupLayout( textField ); - placeComponents( textField ); - setupListeners(); - enableButtons( false ); - } - - public void setValue( String value ) - { - this.initialValue = value == null ? "" : value; - fieldText.setText( initialValue ); - } - - private void startupComponents( boolean textField ) - { - if( !textField ) - { - ((JTextArea) fieldText).setWrapStyleWord( true ); - ((JTextArea) fieldText).setLineWrap( true ); - } - new CopyPasteHandler(fieldText); - scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - buttonSave.setMargin( new Insets(0,0,0,0) ); - buttonRevert.setMargin( new Insets(0,0,0,0) ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( fieldText ); - } - - private void startupLayout( boolean textField ) - { - TableLayout layout; - if( !textField ) - { - layout = new TableLayout( - new double[]{ TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM }, - new double[]{ TableLayout.MINIMUM, TableLayout.FILL } ); - } - else - { - layout = new TableLayout( - new double[]{ TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM }, - new double[]{ TableLayout.MINIMUM } ); - } - this.setLayout( layout ); - } - - private void placeComponents( boolean textField ) - { - if( ! textField ) - { - this.add( scroll, new TableLayoutConstraints( 0, 1, 2, 1) ); - this.add( buttonSave, new TableLayoutConstraints( 1, 0 ) ); - this.add( buttonRevert, new TableLayoutConstraints( 2, 0 ) ); - } - else - { - this.add( fieldText, new TableLayoutConstraints( 0, 0 ) ); - this.add( buttonSave, new TableLayoutConstraints( 1, 0 ) ); - this.add( buttonRevert, new TableLayoutConstraints( 2, 0 ) ); - } - } - - private void setupListeners() - { - buttonSave.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - save(); - } - } ); - buttonRevert.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revert(); - } - } ); - fieldText.addCaretListener( new CaretListener() - { - @Override - public void caretUpdate( CaretEvent e ) - { - enableButtons( !initialValue.equals( fieldText.getText() ) && ( validator == null || validator.isValid( fieldText.getText() ) ) ); - } - } ); - } - - private void enableButtons( boolean enable ) - { - buttonRevert.setEnabled( enable ); - buttonSave.setEnabled( enable ); - } - - private void save() - { - enableButtons( false ); - firePropertyChange( ACTION_SAVE, initialValue, fieldText.getText() ); - initialValue = fieldText.getText(); - } - - private void revert() - { - fieldText.setText( initialValue ); - enableButtons( false ); - firePropertyChange( ACTION_REVERT, fieldText.getText(), initialValue ); - } - - @Override - public void setEnabled( boolean enabled ) - { - fieldText.setEnabled( enabled ); - if( enabled ) - { - fieldText.requestFocusInWindow(); - } - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafTextDialog.java b/trunk/SIPRPSoft/src/leaf/ui/LeafTextDialog.java deleted file mode 100644 index 5364670b..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafTextDialog.java +++ /dev/null @@ -1,170 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.JTextArea; - -import siprp.ui.SIPRPFrame; - -public class LeafTextDialog extends JDialog -{ - private static final long serialVersionUID = 1L; - - private static final Dimension buttonSize = new Dimension( 30, 20 ); - - private static final Dimension textSize = new Dimension( 200, 20 ); - - private static final Dimension expandedTextSize = new Dimension( 300, 200 ); - - private String text = null; - - private String defaultText = null; - - private boolean expanded = true; - - private final JTextArea textArea = new JTextArea(); - private final LeafButton expandButton = new LeafButton( "+" ); - private final LeafButton okButton = new LeafButton( "Ok" ); - private final LeafButton cancelButton = new LeafButton( "X" ); - - private TableLayout layout = null; - private TableLayout expandedLayout = null; - - /** Creates a new instance of JCalendarDialog */ - public LeafTextDialog( LeafWindow parentFrame, JComponent parent, String defaultText, boolean expanded ) - { - super( parentFrame ); - this.defaultText = defaultText == null ? "" : defaultText; - this.text = this.defaultText; - setModal( true ); - setContentPane( new LeafGradientPanel() ); - textArea.setText( text ); - expandButton.setPreferredSize( buttonSize ); - cancelButton.setPreferredSize( buttonSize ); - okButton.setPreferredSize( buttonSize ); - setupLayout(); - setUndecorated( true ); - setDefaultCloseOperation( SIPRPFrame.DO_NOTHING_ON_CLOSE ); - getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); - setLocationRelativeTo( null ); - this.expanded = expanded; - expand( expanded ); - addListeners(); - setVisible( true ); - } - - private void setupLayout() - { - double[] cols = new double[] { - TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED, TableLayout.PREFERRED - }; - double[] rows = new double[] { - TableLayout.PREFERRED - }; - layout = new TableLayout( cols, rows ); - - cols = new double[] { - TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED, TableLayout.PREFERRED - }; - rows = new double[] { - TableLayout.PREFERRED, TableLayout.FILL - }; - expandedLayout = new TableLayout( cols, rows ); - } - - private void placeComponents(boolean expand) - { - if(expand) - { - getContentPane().add( expandButton, new TableLayoutConstraints( 0, 0 ) ); - getContentPane().add( new JPanel(), new TableLayoutConstraints( 0, 1 ) ); - getContentPane().add( textArea, new TableLayoutConstraints( 1, 0,1,1 ) ); - getContentPane().add( okButton, new TableLayoutConstraints( 2, 0 ) ); - getContentPane().add( cancelButton, new TableLayoutConstraints( 3, 0 ) ); - getContentPane().add( new JPanel(), new TableLayoutConstraints( 2, 1,3,1 ) ); - } - else - { - getContentPane().add( expandButton, new TableLayoutConstraints( 0, 0 ) ); - getContentPane().add( textArea, new TableLayoutConstraints( 1, 0 ) ); - getContentPane().add( okButton, new TableLayoutConstraints( 2, 0 ) ); - getContentPane().add( cancelButton, new TableLayoutConstraints( 3, 0 ) ); - } - - ((JComponent) getContentPane()).setBorder( BorderFactory.createRaisedBevelBorder() ); - -// setSize( expand ? expandedLayout.preferredLayoutSize( this.getContentPane() ) : layout.preferredLayoutSize( this.getContentPane() ) ); - setSize( getLayout().preferredLayoutSize( getRootPane() ) ); - } - - private void setupComponents(boolean expand) - { - getContentPane().setLayout( expand ? expandedLayout : layout); - textArea.setPreferredSize( expand ? expandedTextSize : textSize ); - expandButton.setText( expand ? "-" : "+" ); - placeComponents(expand); - } - - private void expand( boolean expand ) - { - setupComponents(expand); - setResizable( expand ); - } - - private void addListeners() - { - expandButton.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - expanded = !expanded; - expand( expanded ); - } - } ); - - okButton.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - text = textArea.getText(); - close(); - } - } ); - - cancelButton.addActionListener( new ActionListener() - { - - @Override - public void actionPerformed( ActionEvent e ) - { - text = defaultText; - close(); - } - - } ); - } - - public String getText() - { - return text; - } - - public void close() - { - setVisible( false ); - dispose(); - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafTree.java b/trunk/SIPRPSoft/src/leaf/ui/LeafTree.java deleted file mode 100644 index 3059f5f6..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafTree.java +++ /dev/null @@ -1,74 +0,0 @@ -package leaf.ui; - -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; - -import com.evolute.utils.ui.trees.TreeTools; - -public class LeafTree extends JTree -{ - - private static final long serialVersionUID = 1L; - - private final List expandedNodes = new LinkedList(); - - public LeafTree(TreeModel model) - { - super(model); - } - - public void saveExpansionState() - { - expandedNodes.clear(); - TreePath treePath = new TreePath(getRoot()); - savePath( treePath ); - } - - private DefaultMutableTreeNode getRoot() - { - return (DefaultMutableTreeNode) getModel().getRoot(); - } - - private void savePath( TreePath treePath ) - { - if( treePath != null ) - { - Enumeration expanded = getExpandedDescendants(treePath); - if( expanded != null ) - { - while( expanded.hasMoreElements() ) - { - TreePath path = expanded.nextElement(); - if( path != null ) - { - Object leaf = path.getLastPathComponent(); - if( leaf instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode)leaf).getUserObject(); - if( userObject != null ) - { - expandedNodes.add(userObject); - } - } - } - savePath(path); - } - } - } - } - - public void loadExpansionState() - { - for( Object userObject : expandedNodes ) - { - TreeTools.expandNodeForObject( userObject, this ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafUIConstants.java b/trunk/SIPRPSoft/src/leaf/ui/LeafUIConstants.java deleted file mode 100644 index 5e4817c6..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafUIConstants.java +++ /dev/null @@ -1,15 +0,0 @@ -package leaf.ui; - -public interface LeafUIConstants -{ - public static final String ICON_NAME_CREATE = "leaf/ui/icons/create.png"; - - public static final String ICON_NAME_EDIT = "leaf/ui/icons/edit.png"; - - public static final String ICON_NAME_REMOVE = "leaf/ui/icons/delete.png"; - - public static final String ICON_NAME_SAVE = "leaf/ui/icons/save.png"; - - public static final String ICON_NAME_REVERT = "leaf/ui/icons/revert.png"; - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/LeafWindow.java b/trunk/SIPRPSoft/src/leaf/ui/LeafWindow.java deleted file mode 100755 index 64fdefb6..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/LeafWindow.java +++ /dev/null @@ -1,940 +0,0 @@ -package leaf.ui; - -import static info.clearthought.layout.TableLayoutConstants.FILL; -import static leaf.ui.LeafLogic.ACTION_CANCEL; -import static leaf.ui.LeafLogic.ACTION_STARTUP; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Cursor; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.lang.annotation.Annotation; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListSelectionModel; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.table.TableModel; - -import leaf.ui.LeafLogic.Action; -import leaf.ui.LeafLogic.LeafLogicActionBinding; -import leaf.ui.LeafLogic.LeafUIActionBinding; -import siprp.ui.SIPRPFrame; - -import com.evolute.adt.Pair; -import com.evolute.utils.tables.BaseTable; -import com.evolute.utils.tables.ColumnizedMappable; -import com.evolute.utils.tables.VectorTableModel; -import com.evolute.utils.tracker.TrackableWindow; - -public class LeafWindow extends SIPRPFrame implements TrackableWindow, ListSelectionListener, TreeSelectionListener, ActionListener, PropertyChangeListener -{ - - private static final long serialVersionUID = 1L; - - private static final int DEFAULT_HEIGHT = 480; - - private static final int DEFAULT_WIDTH = 640; - - /** - * Registers DataComponent in a list of actions - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface ActionActivation - { - /** - * Array of actions to execute when a select is listened in this - * JComponent - * - * @return - */ - String[] onSelect(); - - /** - * Array of actions to execute when a change is listened in this - * JComponent - * - * @return - */ - String[] onChange(); - - } - - /** - * Binds an Object to actions - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface LeafObject - { - - /** - * Actions that use this field - */ - String[] useWith(); - } - - /** - * Declares a JPanel as a leaf - * - * @author tsimao - * - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface LeafPanel - { - } - - /** - * This window's logic controller - */ - private final LeafLogic logicController; - - private List subPanels = new ArrayList(); - - /** - * Actions - */ - private Map mapActionByName = new HashMap(); - - /** - * Fields - */ - private Map> mapWindowOnSelectFieldByActionName = new HashMap>(); - private Map> mapWindowOnChangeFieldByActionName = new HashMap>(); - private Map mapLeafObjectByActionName = new HashMap(); - private Map mapInstanceByField = new HashMap(); - - /** - * Methods - */ - private Map> mapWindowMethodsByActionName = new HashMap>(); - private Map mapLogicMethodByActionName = new HashMap(); - private Map mapInstanceByMethod = new HashMap(); - - /** - * Meta-info - */ - private Map mapAnnotationByObject = new HashMap(); - - /** - * Run later actions - */ - private Queue> listRunLater = new LinkedList>(); - - /** - * Creates a new LeafWindow binded with given 'logicController' - * - * @param logicController - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ - public LeafWindow(LeafLogic logicController) - { - super(); - setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); - this.logicController = logicController; - if( logicController != null ) - { - logicController.addWindow( this ); - } - } - - @Override - public void open() - { - setVisible( true ); - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable() - { - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - @Override - public boolean closeIfPossible() - { - close(); - return true; - } - - @Override - public void refresh() - { - } - - /** - * Aborts current action. Aborts pending actions as well if 'all' is true - * - * @param all - */ - public void abortAction( boolean all ) - { - runGivenAction( ACTION_CANCEL, null ); - throw new LeafRuntimeException( all ); - } - - protected boolean runAction( String actionName ) - { - return runAction( actionName, null ); - } - - /** - * Returns false if an error occurred - * - * @param actionName - * @param argument - * @return - */ - protected boolean runAction( String actionName, Object argument ) - { - boolean ok = true; - if( argument == null ) - { - Field field = mapLeafObjectByActionName.get( actionName ); - if(field != null) - { - Object instance = mapInstanceByField.get( field ); - if( instance != null) - { - try - { - argument = field.get( instance ); - } catch( IllegalArgumentException e ) - { - e.printStackTrace(System.out); - } catch( IllegalAccessException e ) - { - e.printStackTrace( System.out); - } - } - } - } - try - { - runGivenAction( actionName, argument ); - } catch( LeafRuntimeException leafRuntimeException ) - { - ok = !leafRuntimeException.isAbort(); - } - if( ok ) - { - runPendingActions(); - } - else - { - listRunLater.clear(); - } - return ok; - } - - public void runActionLater( String action ) - { - runActionLater( action, null ); - } - - public void runActionLater( String action, Object argument ) - { - if( action != null && mapActionByName.containsKey( action ) ) - { - listRunLater.add( new Pair( action, argument ) ); - } - } - - /** - * Fires ACTION_STARTUP - */ - public void completeSetup() - { - try - { - loadLeafs(); - loadActions(); - loadFields(); - loadMethods(); - runAction( ACTION_STARTUP, null ); - setVisible( true ); - } catch( Exception e ) - { - e.printStackTrace( System.out ); - } - } - - public static void setupTopBottomSimpleActionsPanel(JPanel where, JPanel top, JPanel bottom) - { - TableLayout layout = new TableLayout(new double[]{TableLayout.FILL}, new double[]{TableLayout.MINIMUM, TableLayout.FILL,TableLayout.MINIMUM}); - where.setLayout( layout ); - where.add( top, new TableLayoutConstraints(0,0) ); - where.add( new JPanel(), new TableLayoutConstraints(0,1) ); - where.add( bottom, new TableLayoutConstraints(0,2) ); - } - - public static void setupSimpleDataPanel( JPanel where, String name, JComponent... field ) - { - double[] cols = new double[] { - FILL - }; - double[] rows = new double[field.length]; - for( int i = 0; i < field.length; rows[i++] = TableLayout.PREFERRED ) - ; - rows[rows.length - 1] = FILL; - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - where.setLayout( layout ); - if( name != null ) - { - where.setBorder( BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), name ) ); - } - - for( int i = 0; i < field.length; ++i ) - { - where.add( field[i], new TableLayoutConstraints( 0, i ) ); - } - } - - private void loadLeafs() throws IllegalArgumentException, IllegalAccessException - { - Field fields[] = this.getClass().getDeclaredFields(); - if( fields != null ) - { - for( Field field : fields ) - { - if( field.getAnnotation( LeafPanel.class ) != null && field.get( this ) != null ) - { - subPanels.add( (JPanel) field.get( this ) ); - } - } - } - } - - private void loadActions() throws IllegalArgumentException, IllegalAccessException - { - Field[] allLogicFields = this.logicController.getClass().getFields(); - for( Field field : allLogicFields ) - { - Action action = field.getAnnotation( Action.class ); - if( action != null ) - { - String value = (String) field.get( this ); - if( value != null ) - { - mapActionByName.put( value, action ); - mapWindowMethodsByActionName.put( value, new ArrayList() ); - mapWindowOnSelectFieldByActionName.put( value, new ArrayList() ); - mapWindowOnChangeFieldByActionName.put( value, new ArrayList() ); - } - } - } - } - - private void loadFields( Field[] fields, Object instance ) - { - try - { - for( Field field : fields ) - { - ActionActivation componentBehaviour = field.getAnnotation( ActionActivation.class ); - if( componentBehaviour != null ) - { - String[] allChanges = componentBehaviour.onChange(); - if( allChanges != null ) - { - for( String onChange : allChanges ) - { - if( mapActionByName.containsKey( onChange ) ) - { - // valid action - mapAnnotationByObject.put( field.get( instance ), componentBehaviour ); - mapWindowOnChangeFieldByActionName.get( onChange ).add( field.get( instance ) ); - if( !mapInstanceByField.containsKey( field ) ) - { - addListenerForField( componentBehaviour, field, instance ); - mapInstanceByField.put( field, instance ); - } - } - } - } - - String[] allSelect = componentBehaviour.onSelect(); - if( allSelect != null ) - { - for( String onSelect : allSelect ) - { - if( mapActionByName.containsKey( onSelect ) ) - { - // valid action - mapAnnotationByObject.put( field.get( instance ), componentBehaviour ); - mapWindowOnSelectFieldByActionName.get( onSelect ).add( field.get( instance ) ); - if( !mapInstanceByField.containsKey( field ) ) - { - addListenerForField( componentBehaviour, field, instance ); - mapInstanceByField.put( field, instance ); - } - } - } - } - } - - LeafObject leafObject = field.getAnnotation( LeafObject.class ); - if( leafObject != null ) - { - String[] useWith = leafObject.useWith(); - if( useWith != null ) - { - for( String current : useWith ) - { - if( mapActionByName.containsKey( current ) ) - { - // valid action - mapLeafObjectByActionName.put( current, field ); - mapInstanceByField.put( field, instance ); - } - } - } - } - } - } catch( IllegalAccessException exception ) - { - exception.printStackTrace( System.out ); - } - } - - private void loadFields() - { - Field[] allFields = this.getClass().getDeclaredFields(); - if( allFields != null ) - { - loadFields( allFields, this ); - - } - allFields = logicController.getClass().getDeclaredFields(); - if( allFields != null ) - { - loadFields( allFields, logicController ); - - } - for( JPanel panel : subPanels ) - { - allFields = panel.getClass().getDeclaredFields(); - if( allFields != null ) - { - loadFields( allFields, panel ); - } - } - } - - private void loadWindowMethods( Method[] windowMethods, Object instance ) - { - for( Method method : windowMethods ) - { - LeafUIActionBinding actionBinding = method.getAnnotation( LeafUIActionBinding.class ); - if( actionBinding != null ) - { - String[] actions = actionBinding.action(); - for( String actionName : actions ) - { - if( mapActionByName.containsKey( actionName ) ) - { - // valid action - mapWindowMethodsByActionName.get( actionName ).add( method ); - - mapAnnotationByObject.put( method, actionBinding ); - mapInstanceByMethod.put( method, instance ); - } - } - } - } - } - - private void loadLogicMethods() - { - Method[] allLogicMethods = this.logicController.getClass().getDeclaredMethods(); - if( allLogicMethods != null ) - { - for( Method method : allLogicMethods ) - { - LeafLogicActionBinding actionBinding = method.getAnnotation( LeafLogicActionBinding.class ); - if( actionBinding != null ) - { - String[] actions = actionBinding.actions(); - if( actions != null ) - { - for( String actionName : actions ) - { - if( mapActionByName.containsKey( actionName ) ) - { - // valid action - mapAnnotationByObject.put( method, actionBinding ); - mapLogicMethodByActionName.put( actionName, method ); - mapInstanceByMethod.put( method, logicController ); - } - } - } - } - } - } - } - - private void loadMethods() - { - loadLogicMethods(); - - Method[] allWindowMethods = this.getClass().getDeclaredMethods(); - if( allWindowMethods != null ) - { - loadWindowMethods( allWindowMethods, this ); - } - - for( JPanel panel : subPanels ) - { - allWindowMethods = panel.getClass().getDeclaredMethods(); - if( allWindowMethods != null ) - { - loadWindowMethods( allWindowMethods, panel ); - } - } - - } - - private Object getObjectForAction( String actionName ) - { - Object result = null; - Field field = mapLeafObjectByActionName.get( actionName ); - if( field != null ) - { - Object instance = mapInstanceByField.get( field ); - if( instance != null ) - { - try - { - result = field.get( instance ); - } catch( IllegalArgumentException e ) - { - e.printStackTrace(); - } catch( IllegalAccessException e ) - { - e.printStackTrace(); - } - } - } - return result; - } - - public void runPendingActions() - { - while( listRunLater.size() > 0 ) - { - Pair p = listRunLater.poll(); - runAction( p.getLeft(), p.getRight() ); - } - } - - /** - * Executes given action - */ - private void runGivenAction( String actionName, Object argument ) - { - System.out.println( "Running: " + actionName ); - try - { - this.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ); - if( actionName != null && mapActionByName.containsKey( actionName ) ) - { - Action action = mapActionByName.get( actionName ); - if( action.isSave() ) - { - Object windowArgument = getObjectForAction( actionName ); - if( windowArgument == null ) - { - windowArgument = argument; - } - Object logicArgument = windowArgument; - for( Method currentWindowMethod : mapWindowMethodsByActionName.get( actionName ) ) - { - Object currentLogicArgument = runWindowMethod( currentWindowMethod, windowArgument != null ? windowArgument : argument ); - logicArgument = logicArgument == null ? currentLogicArgument : logicArgument; - } - runLogicMethod( mapLogicMethodByActionName.get( actionName ), logicArgument ); - } - else - { - Object windowArgument = runLogicMethod( mapLogicMethodByActionName.get( actionName ), argument ); - for( Method currentWindowMethod : mapWindowMethodsByActionName.get( actionName ) ) - { - runWindowMethod( currentWindowMethod, windowArgument != null ? windowArgument : argument ); - } - } - } - } finally - { - this.setCursor( Cursor.getDefaultCursor() ); - } - } - - private Object runLogicMethod( Method logicMethod, Object argument ) throws LeafRuntimeException - { - Object result = null; - try - { - if( logicMethod != null ) - { - if( logicMethod.getParameterTypes().length > 0 ) - { - result = logicMethod.invoke( logicController, argument ); - } - else - { - result = logicMethod.invoke( logicController ); - } - } - } catch( IllegalArgumentException e ) - { - System.out.println("Error in: " + logicMethod.getName() ); - System.out.println("Got: " + argument + " expected: " + (logicMethod.getParameterTypes().length > 0 ? logicMethod.getParameterTypes()[0].getCanonicalName() : "(nothing)")); - e.printStackTrace( System.out ); - } catch( IllegalAccessException e ) - { - e.printStackTrace( System.out ); - } catch( InvocationTargetException e ) - { - if( e.getCause() instanceof LeafRuntimeException ) - { - throw (LeafRuntimeException) e.getCause(); - } - else - { - e.printStackTrace( System.out ); - } - } - return result; - } - - private Object runWindowMethod( Method windowMethod, Object argument ) throws LeafRuntimeException - { - Object result = null; - try - { - if( windowMethod != null ) - { - if( windowMethod.getParameterTypes().length > 0 ) - { - result = windowMethod.invoke( mapInstanceByMethod.get( windowMethod ), argument ); - } - else - { - result = windowMethod.invoke( mapInstanceByMethod.get( windowMethod ) ); - } - } - } catch( IllegalArgumentException e ) - { - System.out.println("Error in: " + windowMethod.getName() ); - System.out.println("Got: " + argument + " expected: " + (windowMethod.getParameterTypes().length > 0 ? windowMethod.getParameterTypes()[0].getCanonicalName() : "(nothing)")); - e.printStackTrace( System.out ); - } catch( IllegalAccessException e ) - { - e.printStackTrace( System.out ); - } catch( InvocationTargetException e ) - { - if( e.getCause() instanceof LeafRuntimeException ) - { - throw (LeafRuntimeException) e.getCause(); - } - else - { - e.printStackTrace( System.out ); - } - } - return result; - } - - private void addListenerForField( ActionActivation annotation, Field field, Object instance ) - { - if( instance instanceof SIPRPFrame || instance instanceof JPanel ) - { - try - { - Object value = field.get( instance ); - if( value instanceof BaseTable ) - { - ((BaseTable) value).getSelectionModel().addListSelectionListener( this ); - } - else if( value instanceof JTree ) - { - ((JTree) value).addTreeSelectionListener( this ); - } - else if( value instanceof JButton ) - { - ((JButton) value).addActionListener( this ); - } - else if( value instanceof LeafInputField ) - { - ((LeafInputField) value).addPropertyChangeListener( this ); - } - } catch( IllegalAccessException e ) - { - e.printStackTrace( System.out ); - } catch( NullPointerException e ) - { - e.printStackTrace( System.out ); - } - } - } - - private Object getArgumentListSelectionEvent( String actionName, ListSelectionEvent event ) - { - Object source = event.getSource(); - List allComponents = mapWindowOnSelectFieldByActionName.get( actionName ); - for( Object component : allComponents ) - { - if( component instanceof BaseTable && ((BaseTable) component).getSelectionModel().equals( source ) ) - { - int [] indexes = ((BaseTable) component).getSelectedRows(); - if( indexes != null && indexes.length > 0 ) - { - TableModel model = ((BaseTable) component).getModel(); - if( model instanceof VectorTableModel ) - { - if(indexes.length == 1 && indexes[0] > -1) - { - return ((ColumnizedMappable) ((VectorTableModel) model).getRowAt( indexes[0] )).getID(); - } - else - { - List allSelected = new ArrayList(); - for(int i = 0; i < indexes.length; ++i) - { - allSelected.add( ((ColumnizedMappable) ((VectorTableModel) model).getRowAt( indexes[0] )).getID() ); - } - return allSelected; - } - } - else if( model instanceof LeafTableModel ) - { - if(indexes.length == 1 && indexes[0] > -1) - { - return ((LeafTableModel) model).getKey( indexes[0] ); - } - else - { - List allSelected = new ArrayList(); - for(int i = 0; i < indexes.length; ++i) - { - allSelected.add( ((LeafTableModel) model).getKey( indexes[0] )); - } - return allSelected; - } - } - } - } - } - return null; - } - - private List getActionListSelectionEvent( ListSelectionEvent event ) - { - List result = new ArrayList(); - if( event.getSource() instanceof DefaultListSelectionModel ) - { - DefaultListSelectionModel model = (DefaultListSelectionModel) event.getSource(); - BaseTable table = null; - for( List allComponents : mapWindowOnSelectFieldByActionName.values() ) - { - // for each registered table - for( Object component : allComponents ) - { - if( component instanceof BaseTable && ((BaseTable) component).getSelectionModel().equals( model ) ) - { - table = (BaseTable) component; - } - if( table != null ) - { - break; - } - } - if( table != null ) - { - break; - } - } - Annotation an = mapAnnotationByObject.get( table ); - if( an != null && an instanceof ActionActivation ) - { - String[] actions = ((ActionActivation) an).onSelect(); - for( String actionName : actions ) - { - result.add( actionName ); - } - } - } - return result; - } - - // returns selected node - private Object getArgumentTreeSelectionEvent( String actionName, TreeSelectionEvent event ) - { - List components = mapWindowOnSelectFieldByActionName.get( actionName ); - for( Object component : components ) - { - if( component instanceof JTree && event.getPath() != null ) - { - Object[] nodes = event.getPath().getPath(); - if( nodes != null && nodes.length > 0 ) - { - return nodes[nodes.length - 1]; - } - } - } - return null; - } - - private List getActionTreeSelectionEvent( TreeSelectionEvent event ) - { - List result = new ArrayList(); - Annotation an = mapAnnotationByObject.get( event.getSource() ); - if( an != null && an instanceof ActionActivation ) - { - String[] actions = ((ActionActivation) an).onSelect(); - for( String actionName : actions ) - { - result.add( actionName ); - } - } - return result; - } - - private List getActionActionEvent( ActionEvent event ) - { - List result = new ArrayList(); - Annotation an = mapAnnotationByObject.get( event.getSource() ); - if( an != null && an instanceof ActionActivation ) - { - String[] actions = ((ActionActivation) an).onSelect(); - for( String actionName : actions ) - { - result.add( actionName ); - } - } - return result; - } - - private List getActionsForPropertyChangeEvent( PropertyChangeEvent evt ) - { - List result = new ArrayList(); - Annotation an = mapAnnotationByObject.get( evt.getSource() ); - if( an != null ) - { - if( an instanceof ActionActivation ) - { - if( evt.getSource() instanceof LeafInputField ) - { - if( LeafInputField.PROPERTY_CHANGED_CONSTANT.equals( evt.getPropertyName() ) ) - { - String[] actions = ((ActionActivation) an).onChange(); - for( String actionName : actions ) - { - result.add( actionName ); - } - } - } - } - } - return result; - } - - @Override - public void valueChanged( TreeSelectionEvent event ) - { - List actions = getActionTreeSelectionEvent( event ); - for( String action : actions ) - { - Object argument = getArgumentTreeSelectionEvent( action, event ); - if( !runAction( action, argument ) ) - { - break; - } - } - } - - /** - * Listens to ListSelectionEvents - */ - @Override - public void valueChanged( ListSelectionEvent event ) - { - if( !event.getValueIsAdjusting() ) - { - List actionNames = getActionListSelectionEvent( event ); - for( String action : actionNames ) - { - Object argument = getArgumentListSelectionEvent( action, event ); - if( !runAction( action, argument ) ) - { - break; - } - } - } - } - - @Override - public void actionPerformed( ActionEvent event ) - { - List actionNames = getActionActionEvent( event ); - if( actionNames.size() > 0 ) - { - for( int i = 1; i < actionNames.size(); ++i ) - { - runActionLater( actionNames.get( i ) ); - } - runAction( actionNames.get( 0 ) ); - } - } - - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - List actionNames = getActionsForPropertyChangeEvent( evt ); - if( actionNames.size() > 0 ) - { - for( int i = 1; i < actionNames.size(); ++i ) - { - runActionLater( actionNames.get( i ) ); - } - runAction( actionNames.get( 0 ) ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/SimpleTable.java b/trunk/SIPRPSoft/src/leaf/ui/SimpleTable.java deleted file mode 100644 index 756cbb51..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/SimpleTable.java +++ /dev/null @@ -1,84 +0,0 @@ -package leaf.ui; - -import java.util.List; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionListener; - -import com.evolute.utils.tables.BaseTable; -import com.evolute.utils.tables.VectorTableModel; - -public class SimpleTable extends JScrollPane -{ - - private static final long serialVersionUID = 1L; - - private final VectorTableModel model; - - private final BaseTable table; - - public SimpleTable( String ... columnName ) - { - model = new VectorTableModel( columnName ); - table = new BaseTable( model ); - setViewportView(table); - setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - } - - public VectorTableModel getModel() - { - return model; - } - - public BaseTable getTable() - { - return table; - } - - public void setTitle(String title) - { - setBorder(BorderFactory.createTitledBorder(title)); - } - - public void addListSelectionListener(ListSelectionListener listener){ - table.getSelectionModel().addListSelectionListener(listener); - } - - public void setRows( Vector rows ) - { - model.setValues( rows ); - } - - public ROW_CLASS getSelectedRow() - { - ROW_CLASS result = null; - int index = table.getSelectedRow(); - if( index > -1 ) - { - result = model.getRowAt( index ); - } - return result; - } - - public List getSelectedRows() - { - List result = null; - int [] index = table.getSelectedRows(); - for( int i = 0; i < index.length; ++i ) - { - result.add( model.getRowAt( index[i] ) ); - } - return result; - } - - public void clear() - { - model.clearAll(); - } - -} diff --git a/trunk/SIPRPSoft/src/leaf/ui/TreeInserterDialog.java b/trunk/SIPRPSoft/src/leaf/ui/TreeInserterDialog.java deleted file mode 100644 index a56a6283..00000000 --- a/trunk/SIPRPSoft/src/leaf/ui/TreeInserterDialog.java +++ /dev/null @@ -1,323 +0,0 @@ -package leaf.ui; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import com.evolute.swing.dialog.EvoDialog; -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.images.ImageException; -import com.evolute.utils.images.ImageIconLoader; -import com.evolute.utils.ui.trees.TreeTools; - - - -public class TreeInserterDialog extends EvoDialog -{ - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_ADD = "leaf/ui/icons/add.png"; - - private static final String ICON_NAME_REM = "leaf/ui/icons/rem.png"; - - private final DefaultMutableTreeNode newRoot = new DefaultMutableTreeNode(); - - private final DefaultTreeModel newModel = new DefaultTreeModel( newRoot ); - - private final JTree newTree = new JTree( newModel ); - - private final JScrollPane newScroll = new JScrollPane( newTree ); - - private final DefaultMutableTreeNode allRoot; - - private final DefaultTreeModel allModel; - - private final JTree allTree; - - private final JScrollPane allScroll; - - private JButton buttonAdd = null; - - private JButton buttonRemove = null; - - private final JButton buttonOK = new JButton( "OK" ); - - private final JButton buttonCancel = new JButton( "Cancelar" ); - - private static List expandedNodes = new LinkedList(); - - public TreeInserterDialog( String title, DefaultMutableTreeNode root ) - { - this.allRoot = root; - this.allModel = new DefaultTreeModel( allRoot ); - this.allTree = new JTree( allModel ); - this.allScroll = new JScrollPane( allTree ); - this.setTitle( title ); - try - { - buttonAdd = new JButton( ImageIconLoader.loadImageIcon( ICON_NAME_ADD ) ); - buttonRemove = new JButton( ImageIconLoader.loadImageIcon( ICON_NAME_REM ) ); - } - catch( ImageException e ) - { - ErrorLogger.logException( e ); - } - catch ( IOException e ) - { - ErrorLogger.logException( e ); - } - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - loadExpansionState(); - setEnabled(); - maximize(); - this.setModal( true ); - this.setVisible( true ); - } - - private void loadExpansionState() - { - TreeTools.refreshTree( allTree, allRoot, expandedNodes.isEmpty() ); - for( Object userObject : expandedNodes ) - { - TreeTools.expandNodeForObject( userObject, allTree ); - } - } - - private void startupComponents() - { - newTree.setRootVisible( false ); - newTree.getSelectionModel().setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION ); - allTree.setRootVisible( false ); - allTree.getSelectionModel().setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - allScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - allScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - newScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - newScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - buttonAdd.setToolTipText( "Adicionar" ); - buttonRemove.setToolTipText( "Remover" ); - buttonAdd.setMargin( new Insets(0,0,0,0) ); - buttonRemove.setMargin( new Insets(0,0,0,0) ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( - new double[]{ TableLayout.FILL, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM }, - new double[]{ TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM } - ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - getContentPane().setLayout( layout ); - } - - private void placeComponents() - { - getContentPane().add( new JLabel("Todos"), new TableLayoutConstraints( 0,0 ) ); - getContentPane().add( new JLabel("a adicionar..."), new TableLayoutConstraints( 2,0,4,0 ) ); - getContentPane().add( allScroll, new TableLayoutConstraints( 0,1,0,4 ) ); - getContentPane().add( buttonAdd, new TableLayoutConstraints( 1,1 ) ); - getContentPane().add( buttonRemove, new TableLayoutConstraints( 1,3 ) ); - getContentPane().add( newScroll, new TableLayoutConstraints( 2,1,4,3 ) ); - getContentPane().add( buttonOK, new TableLayoutConstraints( 3,4 ) ); - getContentPane().add( buttonCancel, new TableLayoutConstraints( 4,4 ) ); - } - - private void startupListeners() - { - buttonAdd.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - move( allTree, newTree ); - } - } ); - buttonRemove.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - move( newTree, allTree ); - } - } ); - buttonOK.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - ok(); - } - } ); - buttonCancel.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - cancel(); - } - } ); - allTree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener(){ - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - } - } ); - newTree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener(){ - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - } - } ); - } - - private void move( JTree from, JTree to ) - { - TreePath [] paths = from.getSelectionPaths(); - if( paths != null ) - { - DefaultMutableTreeNode fromRoot = (DefaultMutableTreeNode) from.getModel().getRoot(); - DefaultMutableTreeNode toRoot = (DefaultMutableTreeNode) to.getModel().getRoot(); - for( TreePath path : paths ) - { - for( int i = 1; i < path.getPathCount(); ++i ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getPathComponent( i ); - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getPathComponent( i-1 ); - if( node != null && parent != null ) - { - DefaultMutableTreeNode exists = TreeTools.findNodeWithUserObject( node.getUserObject(), toRoot ); - if( exists == null ) - { - add(node, parent.getUserObject(), toRoot, path.getPathCount() == i + 1 ); - } - else if( i + 1 == path.getPathCount() ) - { - TreeTools.merge( exists, node ); - } - } - } - removeNode( (DefaultMutableTreeNode) path.getLastPathComponent(), fromRoot ); - } - TreeTools.refreshTree( from, fromRoot, true ); - TreeTools.refreshTree( to, toRoot, true ); - } - } - - private void removeNode( DefaultMutableTreeNode node, DefaultMutableTreeNode root ) - { - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent(); - node.removeFromParent(); - if( parent != null && parent.getChildCount() == 0 ) - { - removeNode( parent, root ); - } - } - - private void add( DefaultMutableTreeNode node, Object parent, DefaultMutableTreeNode where, boolean fullClone ) - { - DefaultMutableTreeNode parentNode = TreeTools.findNodeWithUserObject( parent, where ); - if( parentNode == null ) - { - parentNode = where; - } - parentNode.add( fullClone ? TreeTools.cloneFullNode(node) : (DefaultMutableTreeNode) node.clone() ); - } - - private void ok() - { - close(); - } - - private void cancel() - { - newRoot.removeAllChildren(); - close(); - } - - private void close() - { - saveExpandedState(); - setVisible( false ); - } - - private void setEnabled() - { - boolean allSelected = allTree.getSelectionPath() != null; - boolean newSelected = newTree.getSelectionPath() != null; - boolean somethingToAdd = newRoot.getChildCount() > 0; - buttonAdd.setEnabled( allSelected ); - buttonRemove.setEnabled( newSelected ); - buttonOK.setEnabled( somethingToAdd ); - } - - public DefaultMutableTreeNode getResult() - { - return newRoot; - } - - private void saveExpandedState( ) - { - expandedNodes.clear(); - if( allTree != null ) - { - Object root = allTree.getModel().getRoot(); - if( root != null ) - { - savePath( new TreePath(root) ); - } - } - } - - private void savePath( TreePath treePath ) - { - if( treePath != null ) - { - Enumeration expanded = allTree.getExpandedDescendants(treePath); - if( expanded != null ) - { - while( expanded.hasMoreElements() ) - { - TreePath path = expanded.nextElement(); - if( path != null ) - { - Object leaf = path.getLastPathComponent(); - if( leaf instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode)leaf).getUserObject(); - if( userObject != null ) - { - expandedNodes.add(userObject); - } - } - } - savePath(path); - } - } - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/Main.java b/trunk/SIPRPSoft/src/siprp/Main.java index 5c2395c2..552077e0 100644 --- a/trunk/SIPRPSoft/src/siprp/Main.java +++ b/trunk/SIPRPSoft/src/siprp/Main.java @@ -22,6 +22,7 @@ import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import shst.SHSTPropertiesConstants; +import shst.SHSTShutdownHook; import shst.lembretes.LembretesDaemon; import siprp.clientes.AvisosPanel; import siprp.companydataloaders.SIPRPPropertiesLoader; @@ -77,7 +78,7 @@ public class Main implements com.evolute.utils.ui.window.Connector UIManager.put( "FormattedTextField.inactiveForeground", ColorUIResource.BLACK ); UIManager.put( "FormattedTextField.foreground", ColorUIResource.RED.darker() ); - new SIPRPShutdownHook().init(); + new SHSTShutdownHook().init(); new SIPRPUIInitializer().doInit(); diff --git a/trunk/SIPRPSoft/src/siprp/SIPRPShutdownHook.java b/trunk/SIPRPSoft/src/siprp/SIPRPShutdownHook.java deleted file mode 100644 index ef10365c..00000000 --- a/trunk/SIPRPSoft/src/siprp/SIPRPShutdownHook.java +++ /dev/null @@ -1,39 +0,0 @@ -package siprp; - -import siprp.higiene.relatorio.MedidasRiscosDeleterController; - -import com.evolute.threads.EvoShutdownHook; -import com.evolute.utils.error.ErrorLogger; - -public class SIPRPShutdownHook extends EvoShutdownHook -{ - - public SIPRPShutdownHook() - { - - } - - - public void execute() - { - MedidasRiscosDeleterController controller = MedidasRiscosDeleterController.getInstance(); - System.out.println( "\nChecking " + controller.getThreads().size() + " threads ..." ); - for ( Thread deleter : controller.getThreads() ) - { - System.out.println( "\nChecking " + deleter.getName() + " ... Running ? " + deleter.isAlive() ); - if ( deleter.isAlive() ) - { - try - { - System.out.println( "\nWaiting for <" + deleter + "> ... " ); - deleter.join(); - } - catch ( InterruptedException e ) - { - ErrorLogger.logException( e ); - } - } - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/SIPRPTracker.java b/trunk/SIPRPSoft/src/siprp/SIPRPTracker.java index b4876428..207a1798 100644 --- a/trunk/SIPRPSoft/src/siprp/SIPRPTracker.java +++ b/trunk/SIPRPSoft/src/siprp/SIPRPTracker.java @@ -15,12 +15,17 @@ import javax.swing.tree.DefaultMutableTreeNode; import shst.SHSTPropertiesConstants; import shst.SHSTTrackerInterface; import shst.cursos.CursosWindowAdapter; +import shst.higiene.gestao.GestaoRelatorioWindow; import shst.higiene.mapa.MapaHigieneWindow; import shst.higiene.marcacoes.MarcacoesHigieneInterface; import shst.higiene.marcacoes.MarcacoesHigieneWindow; +import shst.higiene.relatorio.RelatorioHigieneSegurancaWindow; import shst.lembretes.LembretesMultiWindow; import shst.medicina.MedicinaWindow; import shst.medicina.MedicinaWindowInterface; +import shst.medicina.exames.ui.RecepcaoExamesWindow; +import shst.medicina.locais_analise.EnviarAnalisesWindow; +import shst.medicina.locais_realizacao.LocaisRealizacaoWindow; import shst.medicina.multi.MultiMarcacoesWindow; import shst.medicina.presencas.RegistarPresencasWindow; import shst.medicina.prestadores.PrestadoresWindow; @@ -29,12 +34,7 @@ import siprp.companydataloaders.SIPRPPropertiesLoader; import siprp.cursos.SIPRPCursosInit; import siprp.estatistica.EstatisticaWindow; import siprp.ficha.FichaWindow; -import siprp.higiene.gestao.GestaoRelatorioWindow; -import siprp.higiene.relatorio.RelatorioHigieneSegurancaWindow; import siprp.impressaofichas.ImpressaoFichasWindow; -import siprp.medicina.exames.ui.RecepcaoExamesWindow; -import siprp.medicina.locais_analise.EnviarAnalisesWindow; -import siprp.medicina.locais_realizacao.LocaisRealizacaoWindow; import siprp.pesquisas.RelatorioAnualWindow; import com.evolute.module.cursos.CursosWindow; @@ -57,7 +57,7 @@ public class SIPRPTracker extends WindowTracker implements SHSTTrackerInterface public static final String MEDICINA_MARCACOES = "Marca\u00e7\u00f5es"; public static final String MEDICINA_MULTI_MARCACOES = MultiMarcacoesWindow.TITLE; public static final String MEDICINA_LOCAIS = "Locais de Realiza\u00e7\u00e3o"; - public static final String MEDICINA_ENVIO_ANALISES= EnviarAnalisesWindow.TITLE; + public static final String MEDICINA_ENVIO_ANALISES = EnviarAnalisesWindow.TITLE; public static final String MEDICINA_PRESENCAS = "Presen\u00e7as"; public static final String HIGIENE_SEGURANCA = "Higiene e Seguran\u00e7a"; public static final String RELATORIO_ANUAL = "Relat\u00f3rio Anual"; diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/AdicionarPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/AdicionarPanel.java deleted file mode 100644 index 172774a8..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/AdicionarPanel.java +++ /dev/null @@ -1,131 +0,0 @@ -package siprp.higiene.gestao; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; - -public abstract class AdicionarPanel extends SIPRPLazyLoadedPanel -{ - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png"; - - protected final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE ); - - protected final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT ); - - public static final String SELECTION_CHANGED = "SELECTION_CHANGED"; - - protected final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - protected final DefaultTreeModel model = new DefaultTreeModel( root ); - - protected final LeafTree tree = new LeafTree( model ); - - protected final JScrollPane scroll = new JScrollPane( tree ); - - public AdicionarPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonAdicionar.setEnabled( false ); - buttonRemover.setEnabled( false ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1 ) ); - } - - private void startupListeners() - { - buttonAdicionar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - add(); - } - } ); - buttonRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - rem(); - } - } ); - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object selection = path.getLastPathComponent(); - firePropertyChange( SELECTION_CHANGED, null, selection ); - } - setEnabled(); - } - } ); - } - - protected abstract void rem(); - - protected abstract void add(); - - protected abstract void setEnabled(); - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/EmpresaPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/EmpresaPanel.java deleted file mode 100644 index f2fa218b..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/EmpresaPanel.java +++ /dev/null @@ -1,158 +0,0 @@ -package siprp.higiene.gestao; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Component; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.List; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JTabbedPane; - -import leaf.ui.LeafDialog; -import shst.data.outer.EmpresasData; -import shst.data.provider.MedicinaDataProvider; - -import com.evolute.utils.error.ErrorLogger; - -public class EmpresaPanel extends SIPRPLazyLoadedPanel -{ - - private static final long serialVersionUID = 1L; - - private static final String NULL_EMPRESA = "Nenhuma"; - - private final JComboBox comboEmpresa = new JComboBox(); - - private final JCheckBox checkImpressao = new JCheckBox("Imprimir tabela alargada"); - - private final GerirEmpresaPanel panelEmpresa = new GerirEmpresaPanel(); - - private final GerirEstabelecimentosPanel panelEstabelecimentos = new GerirEstabelecimentosPanel(); - - private final JTabbedPane tabs = new JTabbedPane(); - - private EmpresasData empresa = null; - - public EmpresaPanel() - { - startupListeners(); - startupComponents(); - setupLayout(); - placeComponents(); - } - - private void startupComponents() - { - List empresas = null; - try - { - MedicinaDataProvider medicinaProvider = MedicinaDataProvider.getProvider(); - empresas = medicinaProvider.getAllEmpresas(); - } - catch ( Exception e ) - { - ErrorLogger.logException( e ); - } - - if( empresas != null ) - { - comboEmpresa.addItem( NULL_EMPRESA ); - for( EmpresasData empresa : empresas ) - { - comboEmpresa.addItem( empresa ); - } - } - tabs.addTab( "Empresa", panelEmpresa ); - tabs.addTab( "Estabelecimentos", panelEstabelecimentos ); - } - - private void setupLayout() - { - double[] cols = new double[]{ - TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM - }; - double[] rows = new double[]{ - TableLayout.MINIMUM, TableLayout.FILL, - }; - TableLayout layout = new TableLayout(cols,rows); - layout.setHGap( 10 ); - layout.setVGap( 10 ); - this.setLayout( layout ); - } - - private void placeComponents() - { - this.add( new JLabel( "Empresa" ), new TableLayoutConstraints( 0, 0 ) ); - this.add( comboEmpresa, new TableLayoutConstraints( 1, 0 ) ); - this.add( checkImpressao, new TableLayoutConstraints( 2, 0 ) ); - this.add( tabs, new TableLayoutConstraints( 0, 1, 2, 1 ) ); - } - - private void setEmpresa( EmpresasData empresa ) - { - this.empresa = empresa; - checkImpressao.setSelected( empresa != null && empresa.getImprimir_tabela_alargada() != null && empresa.getImprimir_tabela_alargada() ); - } - - private void startupListeners() - { - checkImpressao.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - try - { - if( empresa != null ) - { - empresa.setImprimir_tabela_alargada( checkImpressao.isSelected() ); - empresa.save(); - } - } - catch( Exception ex ) - { - LeafDialog.error( ex ); - } - } - } ); - comboEmpresa.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - Object item = e.getItem(); - if( item != null && ItemEvent.SELECTED == e.getStateChange() ) - { - if( item instanceof EmpresasData ) - { - panelEmpresa.setEmpresa( (EmpresasData) item ); - panelEstabelecimentos.setEmpresa( (EmpresasData) item ); - EmpresaPanel.this.setEmpresa( (EmpresasData) item ); - } - else - { - panelEmpresa.setEmpresa( null ); - panelEstabelecimentos.setEmpresa( null ); - EmpresaPanel.this.setEmpresa( null ); - } - } - } - } ); - } - - @Override - protected void refresh() - { - Component c = tabs.getSelectedComponent(); - if( c instanceof SIPRPLazyLoadedPanel ) - { - ((SIPRPLazyLoadedPanel)c).init(); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEmpresaPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEmpresaPanel.java deleted file mode 100644 index d91a2e43..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEmpresaPanel.java +++ /dev/null @@ -1,84 +0,0 @@ -package siprp.higiene.gestao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.otilde; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; - -import javax.swing.BorderFactory; - -import shst.data.outer.EmpresasData; -import siprp.higiene.gestao.email.AdicionarEmailsPanel; -import siprp.higiene.gestao.legislacao.AdicionarLegislacaoPanel; -import siprp.higiene.gestao.normalizacao.AdicionarNormalizacaoPanel; -import siprp.higiene.gestao.postos.GerirAreasPanel; -import siprp.higiene.gestao.riscos.AdicionarRiscosPanel; - -public class GerirEmpresaPanel extends SIPRPLazyLoadedPanel -{ - - private static final long serialVersionUID = 1L; - - private final GerirAreasPanel panelAreas = new GerirAreasPanel(); - private final AdicionarRiscosPanel panelRiscos = new AdicionarRiscosPanel(); - private final AdicionarEmailsPanel panelEmails = new AdicionarEmailsPanel(); - private final AdicionarLegislacaoPanel panelLegislacao = new AdicionarLegislacaoPanel(); - private final AdicionarNormalizacaoPanel panelNormalizacao = new AdicionarNormalizacaoPanel(); - - public GerirEmpresaPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - panelAreas.setBorder( BorderFactory.createTitledBorder( "Postos de trabalho" ) ); - panelRiscos.setBorder( BorderFactory.createTitledBorder( "Riscos" ) ); - panelEmails.setBorder( BorderFactory.createTitledBorder( "Emails" ) ); - panelLegislacao.setBorder( BorderFactory.createTitledBorder( "Legisla" + ccedil + atilde + "o" ) ); - panelNormalizacao.setBorder( BorderFactory.createTitledBorder( "Normaliza" + ccedil + otilde + "es" ) ); - panelEmails.setPreferredSize( new Dimension(0,150) ); - } - - private void setupLayout() - { - double [] cols = new double[]{ TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, }; - double [] rows = new double[]{ TableLayout.FILL, TableLayout.FILL }; - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - this.setLayout( layout ); - } - - private void placeComponents() - { - this.add( panelAreas, new TableLayoutConstraints( 0, 0, 0, 1 ) ); - this.add( panelRiscos, new TableLayoutConstraints( 1, 0, 1, 1 ) ); - this.add( panelLegislacao, new TableLayoutConstraints( 2, 0 ) ); - this.add( panelNormalizacao, new TableLayoutConstraints( 2, 1 ) ); - } - - private void startupListeners() - { - } - - public void setEmpresa( EmpresasData empresa ) - { - panelAreas.setEmpresa( empresa ); - panelLegislacao.setEmpresa( empresa ); - panelRiscos.setEmpresa( empresa ); - panelNormalizacao.setEmpresa( empresa ); - } - - @Override - protected void refresh() - { - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEstabelecimentosPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEstabelecimentosPanel.java deleted file mode 100644 index ebd8bdb7..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GerirEstabelecimentosPanel.java +++ /dev/null @@ -1,148 +0,0 @@ -package siprp.higiene.gestao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.BorderFactory; -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import shst.data.outer.EmpresasData; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsPostoData; -import siprp.higiene.gestao.email.AdicionarEmailsPanel; -import siprp.higiene.gestao.legislacao.AdicionarLegislacaoPanel; -import siprp.higiene.gestao.normalizacao.AdicionarNormalizacaoPanel; -import siprp.higiene.gestao.postos.AdicionarAreasPanel; -import siprp.higiene.gestao.riscos.AdicionarRiscosPanel; - -public class GerirEstabelecimentosPanel extends JPanel -{ - - private static final long serialVersionUID = 1L; - - private static final String NULL_ESTABELECIMENTO = "Nenhum"; - - private final JComboBox comboEstabelecimentos = new JComboBox(); - private final JPanel panelAreasRiscos = new JPanel(); - private final AdicionarAreasPanel panelAreas = new AdicionarAreasPanel(); - private final AdicionarRiscosPanel panelRiscos = new AdicionarRiscosPanel(); - private final AdicionarEmailsPanel panelEmails = new AdicionarEmailsPanel(); - private final AdicionarLegislacaoPanel panelLegislacao = new AdicionarLegislacaoPanel(); - private final AdicionarNormalizacaoPanel panelNormalizacao = new AdicionarNormalizacaoPanel(); - - public GerirEstabelecimentosPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - panelAreasRiscos.setBorder( BorderFactory.createTitledBorder( "Riscos por posto de trabalho" ) ); - panelRiscos.setBorder( BorderFactory.createTitledBorder( "Riscos" ) ); - panelEmails.setBorder( BorderFactory.createTitledBorder( "Emails" ) ); - panelLegislacao.setBorder( BorderFactory.createTitledBorder( "Legisla" + ccedil + atilde + "o" ) ); - panelEmails.setPreferredSize( new Dimension(0,150) ); - } - - private void setupLayout() - { - double [] cols = new double[]{ TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, }; - double [] rows = new double[]{ TableLayout.MINIMUM, TableLayout.FILL,TableLayout.FILL, TableLayout.PREFERRED }; - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - this.setLayout( layout ); - - panelAreasRiscos.setLayout( new GridLayout( 1, 2 ) ); - } - - private void placeComponents() - { - panelAreasRiscos.add( panelAreas ); - panelAreasRiscos.add( panelRiscos ); - - this.add( comboEstabelecimentos, new TableLayoutConstraints( 0, 0, 2, 0 ) ); - this.add( panelAreasRiscos, new TableLayoutConstraints( 0, 1, 1, 3 ) ); - this.add( panelLegislacao, new TableLayoutConstraints( 2, 1 ) ); - this.add( panelNormalizacao, new TableLayoutConstraints( 2, 2 ) ); - this.add( panelEmails, new TableLayoutConstraints( 2, 3 ) ); - } - - private void startupListeners() - { - comboEstabelecimentos.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - if( e.getItem() != null && ItemEvent.SELECTED == e.getStateChange() ) - { - if( e.getItem() instanceof EstabelecimentosData ) - { - EstabelecimentosData estabelecimento = (EstabelecimentosData) e.getItem(); - panelAreas.setEstabelecimento( estabelecimento ); - panelEmails.setEstabelecimento( estabelecimento ); - panelLegislacao.setEstabelecimento( estabelecimento ); - panelNormalizacao.setEstabelecimento( estabelecimento ); - } - else - { - EstabelecimentosData estabelecimento = null; - panelAreas.setEstabelecimento( estabelecimento ); - panelEmails.setEstabelecimento( estabelecimento ); - panelLegislacao.setEstabelecimento( estabelecimento ); - panelNormalizacao.setEstabelecimento( estabelecimento ); - } - } - } - } ); - panelAreas.addPropertyChangeListener( AdicionarAreasPanel.SELECTION_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - Object obj = evt.getNewValue(); - if( obj != null && (obj instanceof HsPostoData) ) - { - panelRiscos.setPosto( (HsPostoData) obj ); - } - else - { - panelRiscos.setPosto( null ); - } - } - } ); - } - - public void setEmpresa( EmpresasData empresa ) - { - comboEstabelecimentos.removeAllItems(); - System.out.println("setEmpresa!"); - if( empresa != null ) - { - comboEstabelecimentos.addItem( NULL_ESTABELECIMENTO ); - for( EstabelecimentosData estabelecimento : empresa.fromEstabelecimentos_empresa_id() ) - { - comboEstabelecimentos.addItem( estabelecimento ); - } - if( comboEstabelecimentos.getItemCount() > 0 ) - { - comboEstabelecimentos.setSelectedIndex( 0 ); - } - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GestaoRelatorioWindow.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/GestaoRelatorioWindow.java deleted file mode 100644 index 5a81e190..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GestaoRelatorioWindow.java +++ /dev/null @@ -1,83 +0,0 @@ -package siprp.higiene.gestao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; - -import java.awt.Dimension; - -import javax.swing.JTabbedPane; -import javax.swing.SwingUtilities; - -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.tracker.TrackableWindow; - -public class GestaoRelatorioWindow extends SIPRPFrame implements TrackableWindow -{ - - public static final String TITLE = "Gest" + atilde + "o de Relat" + oacute + "rio de H&S"; - - private static final Dimension SIZE = new Dimension( 1024, 700 ); - - private static final long serialVersionUID = 1L; - - private final JTabbedPane tabs = new JTabbedPane(); - - private final GlobalPanel panelGlobal = new GlobalPanel(); - - private final EmpresaPanel panelEmpresa = new EmpresaPanel(); - - public static void main( String[] args ) - { - GestaoRelatorioWindow window = new GestaoRelatorioWindow(); - window.setDefaultCloseOperation( SIPRPFrame.EXIT_ON_CLOSE ); - window.open(); - } - - public GestaoRelatorioWindow() - { - this.setTitle( TITLE ); - this.setSize( SIZE ); - this.setLocationRelativeTo( null ); - placeComponents(); - } - - private void placeComponents() - { - tabs.addTab( "Global", panelGlobal ); - tabs.addTab( "Por Empresa", panelEmpresa ); - this.setContentPane( tabs ); - } - - @Override - public void open() - { - setVisible( true ); - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable() - { - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - @Override - public boolean closeIfPossible() - { - close(); - return true; - } - - @Override - public void refresh() - { - } - - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GlobalPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/GlobalPanel.java deleted file mode 100644 index a9d94e00..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/GlobalPanel.java +++ /dev/null @@ -1,71 +0,0 @@ -package siprp.higiene.gestao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; - -import java.awt.Component; - -import javax.swing.JTabbedPane; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import siprp.higiene.gestao.equipamentos.GerirEquipamentosPanel; -import siprp.higiene.gestao.legislacao.GerirLegislacaoPanel; -import siprp.higiene.gestao.normalizacao.GerirNormalizacaoPanel; -import siprp.higiene.gestao.riscos.GerirRiscosPanel; - -public class GlobalPanel extends JTabbedPane -{ - - private static final long serialVersionUID = 1L; - - private final GerirRiscosPanel panelRiscos = new GerirRiscosPanel(); - - private final GerirLegislacaoPanel panelLegislacao = new GerirLegislacaoPanel(); - - private final GerirNormalizacaoPanel panelNormalizacao= new GerirNormalizacaoPanel(); - - private final GerirEquipamentosPanel panelEquipamentos = new GerirEquipamentosPanel(); - - public GlobalPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - panelRiscos.init(); - } - - private void startupComponents() - { - addTab( "Riscos", panelRiscos ); - addTab( "Legisla" + ccedil + atilde + "o", panelLegislacao ); - addTab( "Normaliza" + ccedil + atilde + "o", panelNormalizacao ); - addTab( "Equipamentos", panelEquipamentos ); - } - - private void setupLayout() - { - } - - private void placeComponents() - { - } - - private void startupListeners() - { - addChangeListener( new ChangeListener() - { - @Override - public void stateChanged( ChangeEvent e ) - { - Component c = getSelectedComponent(); - if( c instanceof SIPRPLazyLoadedPanel ) - { - ((SIPRPLazyLoadedPanel)c).init(); - } - } - } ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/SIPRPLazyLoadedPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/SIPRPLazyLoadedPanel.java deleted file mode 100644 index 109e8ad3..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/SIPRPLazyLoadedPanel.java +++ /dev/null @@ -1,77 +0,0 @@ -package siprp.higiene.gestao; - -import java.awt.Cursor; - -import javax.swing.SwingUtilities; - -import com.evolute.swing.frame.EvoFrame; -import com.evolute.swing.panel.EvoPanel; -import com.evolute.utils.error.ErrorLogger; - - -public abstract class SIPRPLazyLoadedPanel extends EvoPanel -{ - - private static final long serialVersionUID = 1L; - - private boolean inited = false; - - public synchronized final void doRefresh( ) - { - Runnable run = new Runnable() - { - @Override - public void run() - { - try - { - inited = true; - EvoFrame window = EvoFrame.findParentEvoFrame( SIPRPLazyLoadedPanel.this ); - if( window != null ) - { - window.runAsynchronously( new Runnable() - { - - @Override - public void run() - { - long start = System.currentTimeMillis(); - refresh(); - System.out.println("\n\t" + SIPRPLazyLoadedPanel.this.getClass() + ": took " + ( System.currentTimeMillis() - start ) ); - } - } ); - } - else - { - try - { - setCursor( new Cursor( Cursor.WAIT_CURSOR ) ); - refresh(); - } - finally - { - setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) ); - } - } - } - catch( Exception e ) - { - ErrorLogger.logException( e ); - } - } - - }; - SwingUtilities.invokeLater( run ); - } - - public final void init() - { - if( !inited ) - { - doRefresh(); - } - } - - protected abstract void refresh(); - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/add.png b/trunk/SIPRPSoft/src/siprp/higiene/gestao/add.png deleted file mode 100644 index ff55ed0c..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/gestao/add.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/delete.png b/trunk/SIPRPSoft/src/siprp/higiene/gestao/delete.png deleted file mode 100644 index d7cc9c68..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/gestao/delete.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/email/AdicionarEmailsPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/email/AdicionarEmailsPanel.java deleted file mode 100644 index 3ccc01a1..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/email/AdicionarEmailsPanel.java +++ /dev/null @@ -1,109 +0,0 @@ -package siprp.higiene.gestao.email; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; - -import javax.swing.JOptionPane; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import leaf.ui.LeafDialog; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsEmailData; -import shst.data.outer.HsEmailEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.AdicionarPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarEmailsPanel extends AdicionarPanel -{ - - private static final long serialVersionUID = 1L; - - private EstabelecimentosData estabelecimento = null; - - public void setEstabelecimento( EstabelecimentosData estabelecimento ) - { - this.estabelecimento = estabelecimento; - doRefresh(); - setEnabled(); - } - - @Override - protected void add() - { - try - { - if( estabelecimento != null ) - { - String emailString = JOptionPane.showInputDialog( this, "Email", "Adicionar novo Email", JOptionPane.QUESTION_MESSAGE ); - if( emailString != null ) - { - HsEmailData email = new HsEmailData(); - email.setEmail( emailString ); - email.save(); - HsEmailEstabelecimentoData rel = new HsEmailEstabelecimentoData(); - rel.setToEmail_id( email ); - rel.setToEstabelecimento_id( estabelecimento ); - rel.save(); - doRefresh(); - } - } - } - catch (Exception e) - { - LeafDialog.error( e ); - } - } - - private boolean confirmDelete() - { - return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( - null, "Tem a certeza que deseja remover o email seleccionado?", - "Confirmar remo" + ccedil + atilde + "o", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - } - - @Override - protected void rem() - { - try - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - if( node != null && confirmDelete() ) - { - Object obj = node.getUserObject(); - if( obj instanceof HsEmailEstabelecimentoData ) - { - ((HsEmailEstabelecimentoData) obj).delete(); - doRefresh(); - } - } - } - } - catch (Exception e) - { - LeafDialog.error( e ); - } - } - - @Override - public void refresh() - { - root.removeAllChildren(); - TreeTools.merge( root, HigieneSegurancaLogic.getEmailsForEstabelecimento( estabelecimento ) ); - TreeTools.refreshTree( tree, root, false ); - } - - @Override - protected void setEnabled() - { - buttonAdicionar.setEnabled( estabelecimento != null ); - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/AdicionarEquipamentosPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/AdicionarEquipamentosPanel.java deleted file mode 100644 index e2bf1d73..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/AdicionarEquipamentosPanel.java +++ /dev/null @@ -1,232 +0,0 @@ -package siprp.higiene.gestao.equipamentos; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.TreeInserterDialog; -import shst.data.outer.HsEquipamentoData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.HsRelatorioEquipamentoData; -import shst.logic.HigieneSegurancaLogic; -import shst.logic.node.EquipamentoNode; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarEquipamentosPanel extends JPanel -{ - - private static final long serialVersionUID = 1L; - - public static final String SELECTION_CHANGED = "SELECTION_CHANGED"; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png"; - - private final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private HsRelatorioData relatorio = null; - - public AdicionarEquipamentosPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonAdicionar.setEnabled( false ); - buttonRemover.setEnabled( false ); - buttonAdicionar.setToolTipText( "Adicionar" ); - buttonRemover.setToolTipText( "Remover" ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1 ) ); - } - - private void startupListeners() - { - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - TreePath path = tree.getSelectionPath(); - DefaultMutableTreeNode node = path == null ? null : (DefaultMutableTreeNode)path.getLastPathComponent(); - Object obj = node == null ? null : node.getUserObject(); - HsRelatorioEquipamentoData rel = obj == null ? null : ((obj instanceof HsRelatorioEquipamentoData) ? (HsRelatorioEquipamentoData) obj : null); - firePropertyChange( SELECTION_CHANGED, null, rel == null ? null : rel.toHs_relatorio_id() ); - } - } ); - buttonAdicionar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - add(); - } - } ); - buttonRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - rem(); - } - } ); - } - - private void add() - { - if( relatorio != null ) - { - - DefaultMutableTreeNode allEquipamentos = HigieneSegurancaLogic.getEquipamentosTree(); - TreeInserterDialog dialog = new TreeInserterDialog("Adicionar equipamento",allEquipamentos); - DefaultMutableTreeNode result = dialog.getResult(); - if( result != null ) - { - for( int i = 0; i < result.getChildCount(); ++i ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) result.getChildAt( i ); - Object obj = node.getUserObject(); - if( obj instanceof HsEquipamentoData ) - { - try - { - HsEquipamentoData equipamento = (HsEquipamentoData) obj; - HsRelatorioEquipamentoData relEqui = new HsRelatorioEquipamentoData(); - relEqui.setHs_equipamento( equipamento.getId() ); - relEqui.setToHs_relatorio_id( relatorio ); - relEqui.setMarca( equipamento.getMarca() ); - relEqui.setModelo( equipamento.getModelo() ); - relEqui.setTipo( equipamento.getTipo() ); - relEqui.save(); - } - catch (Exception e) - { - LeafDialog.error( e ); - } - } - } - } - refresh(); - } - } - - private void rem() - { - try - { - TreePath path = tree.getSelectionPath(); - DefaultMutableTreeNode node = path == null ? null : (DefaultMutableTreeNode)path.getLastPathComponent(); - Object obj = node.getUserObject(); - HsRelatorioEquipamentoData rel = obj == null ? null : ((obj instanceof HsRelatorioEquipamentoData) ? (HsRelatorioEquipamentoData) obj : null); - if( rel != null && confirmDelete() ) - { - rel.delete(); - refresh(); - } - } - catch (Exception e) - { - LeafDialog.error( e ); - } - } - - private boolean confirmDelete() - { - return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( - null, "Tem a certeza que deseja remover o equipamento seleccionado?", - "Confirmar remo" + ccedil + atilde + "o", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - } - - private void setEnabled() - { - buttonAdicionar.setEnabled( relatorio != null && relatorio.getIs_submetido() == null ); - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - - public void refresh() - { - root.removeAllChildren(); - if( relatorio != null ) - { - for( HsRelatorioEquipamentoData rel : relatorio.fromHsRelatorioEquipamento_hs_relatorio_id() ) - { - root.add( new EquipamentoNode( rel ) ); - } - } - setEnabled(); - TreeTools.refreshTree( tree, root, false ); - } - - public void setRelatorio( HsRelatorioData relatorio ) - { - this.relatorio = relatorio; - refresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/GerirEquipamentosPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/GerirEquipamentosPanel.java deleted file mode 100644 index d3939d6d..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/equipamentos/GerirEquipamentosPanel.java +++ /dev/null @@ -1,333 +0,0 @@ -package siprp.higiene.gestao.equipamentos; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Date; - -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.LeafUIConstants; -import shst.data.outer.HsEquipamentoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirEquipamentosPanel extends SIPRPLazyLoadedPanel implements CaretListener, LeafUIConstants -{ - - private static final long serialVersionUID = 1L; - - private LeafIconButton buttonSaveRequesito = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private LeafIconButton buttonRevertRequesito = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final JPanel panelButtons = new JPanel(); - - private final JPanel panelTree = new JPanel(); - - private final JPanel panelData = new JPanel(); - - private final JTextField textTipo = new JTextField(20); - - private final JTextField textMarca = new JTextField(20); - - private final JTextField textModelo = new JTextField(20); - - private final LeafButton buttonCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonRemover = LeafIconButton.createDefaultRemoveButton(); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - private final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - public GerirEquipamentosPanel() - { - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void setupListeners() - { - buttonCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criar(); - } - } ); - buttonRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - remover(); - } - } ); - buttonSaveRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - save(); - } - } ); - buttonRevertRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revert(); - } - } ); - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath path = e.getNewLeadSelectionPath(); - if( path != null ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - Object obj = node.getUserObject(); - if( obj instanceof HsEquipamentoData ) - { - textTipo.setText( ((HsEquipamentoData)obj).getTipo() ); - textMarca.setText( ((HsEquipamentoData)obj).getMarca() ); - textModelo.setText( ((HsEquipamentoData)obj).getModelo()); - } - } - else - { - textTipo.setText( "" ); - textMarca.setText( "" ); - textModelo.setText( "" ); - } - setEnabled(); - } - } ); - textTipo.addCaretListener( this ); - textMarca.addCaretListener( this ); - textModelo.addCaretListener( this ); - } - - private void criar() - { - try - { - String tipo = JOptionPane.showInputDialog( this, "Tipo", "Criar novo equipamento", JOptionPane.QUESTION_MESSAGE ); - if( tipo != null ) - { - HsEquipamentoData equipamento = new HsEquipamentoData(); - equipamento.setTipo( tipo ); - equipamento.save(); - doRefresh(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void remover() - { - try - { - HsEquipamentoData equipamento = getSelected(); - if( equipamento != null && confirmDelete() ) - { - equipamento.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - equipamento.save(); - doRefresh(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private boolean confirmDelete() - { - return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( - null, "Tem a certeza que deseja remover o equipamento seleccionado?", - "Confirmar remo" + ccedil + atilde + "o", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - } - - private void save() - { - try - { - HsEquipamentoData equipamento = getSelected(); - if( equipamento != null ) - { - equipamento.setTipo( textTipo.getText() ); - equipamento.setMarca( textMarca.getText() ); - equipamento.setModelo( textModelo.getText() ); - equipamento.save(); - doRefresh(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void revert() - { - HsEquipamentoData equipamento = getSelected(); - if( equipamento != null ) - { - textTipo.setText( equipamento.getTipo() ); - textMarca.setText( equipamento.getMarca() ); - textModelo.setText( equipamento.getModelo() ); - } - } - - private HsEquipamentoData getSelected() - { - Object object = getSelectedObject(); - return object == null ? null : ((object instanceof HsEquipamentoData) ? (HsEquipamentoData) object : null); - } - - private Object getSelectedObject() - { - DefaultMutableTreeNode node = getSelectedNode(); - return node == null ? null : node.getUserObject(); - } - - private DefaultMutableTreeNode getSelectedNode() - { - TreePath path = tree.getSelectionPath(); - return path == null ? null : (DefaultMutableTreeNode) path.getLastPathComponent(); - } - - private void startupComponents() - { - panelTree.setPreferredSize( new Dimension( 400, 400 ) ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setEnabled() - { - HsEquipamentoData equipamento = getSelected(); - buttonRemover.setEnabled( equipamento != null ); - textTipo.setEnabled( equipamento != null ); - textMarca.setEnabled( equipamento != null ); - textModelo.setEnabled( equipamento != null ); - buttonSaveRequesito.setEnabled( false ); - buttonRevertRequesito.setEnabled( false ); - if( equipamento != null ) - { - boolean changed = !textTipo.getText().equals( equipamento.getTipo() ); - changed |= !textMarca.getText().equals( equipamento.getMarca() == null ? "" : equipamento.getMarca() ); - changed |= !textModelo.getText().equals( equipamento.getModelo() == null ? "" : equipamento.getModelo() ); - buttonSaveRequesito.setEnabled( changed ); - buttonRevertRequesito.setEnabled( changed ); - } - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelButtons.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL,TableLayout.MINIMUM,TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM,TableLayout.MINIMUM,TableLayout.MINIMUM, TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelData.setLayout( layout ); - - panelTree.setLayout( new GridLayout( 1,1 ) ); - } - - private void placeComponents() - { - panelButtons.add( buttonCriar, new TableLayoutConstraints( 0, 0 ) ); - panelButtons.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - panelTree.add( scroll, new TableLayoutConstraints( 0, 0 ) ); - - panelData.add( buttonSaveRequesito, new TableLayoutConstraints( 2, 0 ) ); - panelData.add( buttonRevertRequesito, new TableLayoutConstraints( 3, 0 ) ); - panelData.add( new JLabel("Tipo"), new TableLayoutConstraints( 0, 1 ) ); - panelData.add( textTipo, new TableLayoutConstraints( 1, 1, 3, 1 ) ); - panelData.add( new JLabel("Marca"), new TableLayoutConstraints( 0, 2 ) ); - panelData.add( textMarca, new TableLayoutConstraints( 1, 2, 3, 2 ) ); - panelData.add( new JLabel("Modelo"), new TableLayoutConstraints( 0, 3 ) ); - panelData.add( textModelo, new TableLayoutConstraints( 1, 3, 3, 3 ) ); - - add( panelButtons, new TableLayoutConstraints( 0, 0 ) ); - add( panelTree, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - add( panelData, new TableLayoutConstraints( 2, 1 ) ); - } - - @Override - public void refresh() - { - root.removeAllChildren(); - TreeTools.merge( root, HigieneSegurancaLogic.getEquipamentosTree() ); - TreeTools.refreshTree( tree, root, false ); - setEnabled(); - } - - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/AdicionarLegislacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/AdicionarLegislacaoPanel.java deleted file mode 100644 index e1f1ef9a..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/AdicionarLegislacaoPanel.java +++ /dev/null @@ -1,207 +0,0 @@ -package siprp.higiene.gestao.legislacao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import leaf.ui.LeafDialog; -import leaf.ui.TreeInserterDialog; -import shst.data.outer.EmpresasData; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsLegislacaoData; -import shst.data.outer.HsLegislacaoEmpresaData; -import shst.data.outer.HsLegislacaoEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.AdicionarPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarLegislacaoPanel extends AdicionarPanel -{ - -private static final long serialVersionUID = 1L; - - private EmpresasData empresa = null; - - private EstabelecimentosData estabelecimento = null; - - public void setEmpresa( EmpresasData empresa ) - { - this.empresa = empresa; - this.estabelecimento = null; - doRefresh(); - } - - public void setEstabelecimento( EstabelecimentosData estabelecimento ) - { - this.empresa = null; - this.estabelecimento = estabelecimento; - doRefresh(); - } - - @Override - protected void add() - { - DefaultMutableTreeNode allLegislacao = getAllLegislacao(); - removeCurrent( allLegislacao ); - TreeInserterDialog dialog = new TreeInserterDialog( "Adicionar Legisla" + ccedil + atilde + "o", allLegislacao ); - DefaultMutableTreeNode result = dialog.getResult(); - if( result != null ) - { - addResult( result ); - doRefresh(); - } - setEnabled(); - } - - private DefaultMutableTreeNode getAllLegislacao() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - if( empresa != null ) - { - result = HigieneSegurancaLogic.getLegislacaoTreeForEmpresa( null ); - } - else if( estabelecimento != null ) - { - result = HigieneSegurancaLogic.getLegislacaoTreeForEmpresa( estabelecimento.toEmpresa_id() ); - } - return result; - } - - private void removeCurrent( DefaultMutableTreeNode all ) - { - if( all != null && root.getChildCount() == 2 && all.getChildCount() == 2 ) - { - DefaultMutableTreeNode geralAll = (DefaultMutableTreeNode) all.getChildAt( 0 ); - DefaultMutableTreeNode especificaAll = (DefaultMutableTreeNode) all.getChildAt( 1 ); - DefaultMutableTreeNode geralCurrent = (DefaultMutableTreeNode) root.getChildAt( 0 ); - DefaultMutableTreeNode especificaCurrent = (DefaultMutableTreeNode) root.getChildAt( 1 ); - TreeTools.remove( geralAll, geralCurrent ); - TreeTools.removeAllLeafs( especificaAll, especificaCurrent ); - } - } - - private void addResult( DefaultMutableTreeNode root ) - { - try - { - if( root != null ) - { - Object userObject = root.getUserObject(); - if( userObject instanceof HsLegislacaoData ) - { - if( empresa != null ) - { - HsLegislacaoEmpresaData rel = new HsLegislacaoEmpresaData(); - rel.setToEmpresa_id( empresa ); - rel.setToLegislacao_id( ((HsLegislacaoData) userObject ) ); - rel.save(); - } - else if( estabelecimento != null ) - { - HsLegislacaoEstabelecimentoData rel = new HsLegislacaoEstabelecimentoData(); - rel.setToEstabelecimento_id( estabelecimento ); - rel.setToLegislacao_id( ((HsLegislacaoData) userObject ) ); - rel.save(); - } - } - } - for( int i = 0; i < root.getChildCount(); ++i ) - { - DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt( i ); - addResult( child ); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - @Override - public void refresh() - { - root.removeAllChildren(); - if( empresa != null ) - { - TreeTools.merge( root, HigieneSegurancaLogic.getLegislacaoTreeForEmpresa( empresa ) ); - } - else if( estabelecimento != null ) - { - TreeTools.merge( root, HigieneSegurancaLogic.getLegislacaoTreeForEstabelecimento( estabelecimento ) ); - } - setEnabled(); - TreeTools.refreshTree( tree, root, false ); - } - - @Override - protected void setEnabled() - { - buttonAdicionar.setEnabled( empresa != null || estabelecimento != null ); - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - - @Override - protected void rem() - { - try - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - Object obj = node.getUserObject(); - if( obj != null && (obj instanceof HsLegislacaoData) ) - { - if( empresa != null && LeafDialog.confirmDelete( false, false, "legisla" + ccedil + atilde + "o" ) ) - { - removeFromEmpresa( ((HsLegislacaoData) obj ) ); - } - else if( estabelecimento != null && LeafDialog.confirmDelete( false, false, "legisla" + ccedil + atilde + "o" ) ) - { - removeFromEstabelecimento( ((HsLegislacaoData) obj )); - } - doRefresh(); - } - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removeFromEmpresa( HsLegislacaoData legislacao ) throws Exception - { - if( legislacao != null && empresa != null ) - { - for( HsLegislacaoEmpresaData rel : empresa.fromHsLegislacaoEmpresa_empresa_id() ) - { - if( legislacao.equals( rel.toLegislacao_id() ) ) - { - rel.delete(); - break; - } - } - } - } - - private void removeFromEstabelecimento( HsLegislacaoData legislacao ) throws Exception - { - if( legislacao != null && estabelecimento != null ) - { - for( HsLegislacaoEstabelecimentoData rel : estabelecimento.fromHsLegislacaoEstabelecimento_estabelecimento_id() ) - { - if( legislacao.equals( rel.toLegislacao_id() ) ) - { - rel.delete(); - break; - } - } - - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/GerirLegislacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/GerirLegislacaoPanel.java deleted file mode 100644 index e09bd6b3..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/legislacao/GerirLegislacaoPanel.java +++ /dev/null @@ -1,499 +0,0 @@ -package siprp.higiene.gestao.legislacao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.iacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.GridLayout; -import java.awt.LayoutManager; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Date; - -import javax.swing.BorderFactory; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTextAreaEditor; -import leaf.ui.LeafTree; -import leaf.ui.LeafUIConstants; -import shst.data.outer.HsLegislacaoCategoriaData; -import shst.data.outer.HsLegislacaoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.adt.Validator; -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirLegislacaoPanel extends SIPRPLazyLoadedPanel implements LeafUIConstants -{ - - private static final long serialVersionUID = 1L; - - private final JPanel panelGeral = new JPanel(); - - private final JPanel panelCategorias = new JPanel(); - - private final JPanel panelButtonsGeral = new JPanel(); - - private final LeafButton buttonGeralCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonGeralRemover = LeafIconButton.createDefaultRemoveButton(); - - private final JPanel panelButtonsCategoriasCategoria = new JPanel(); - - private final LeafButton buttonCategoriaCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonCategoriaEditar = LeafIconButton.createDefaultEditButton(); - - private final LeafButton buttonCategoriaRemover = LeafIconButton.createDefaultRemoveButton(); - - private final JPanel panelButtonsCategoriasLegislacao = new JPanel(); - - private final LeafButton buttonCategoriasLegislacaoCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonCategoriasLegislacaoRemover = LeafIconButton.createDefaultRemoveButton(); - - private final DefaultMutableTreeNode rootGeral = new DefaultMutableTreeNode(); - - private final DefaultTreeModel modelGeral = new DefaultTreeModel( rootGeral ); - - private final LeafTree treeGeral = new LeafTree( modelGeral ); - - private final JScrollPane scrollGeral = new JScrollPane( treeGeral ); - - private final DefaultMutableTreeNode rootCategorias = new DefaultMutableTreeNode(); - - private final DefaultTreeModel modelCategorias = new DefaultTreeModel( rootCategorias ); - - private final LeafTree treeCategorias = new LeafTree( modelCategorias ); - - private final JScrollPane scrollCategorias = new JScrollPane( treeCategorias ); - - private HsLegislacaoData selectedLegislacaoGeral = null; - - private HsLegislacaoData selectedLegislacaoEspecifica = null; - - private HsLegislacaoCategoriaData selectedCategoria = null; - - private final LeafTextAreaEditor panelData = new LeafTextAreaEditor( new Validator() - { - @Override - public boolean isValid( String object ) - { - return true; - } - } ); - - public GerirLegislacaoPanel() - { - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void startupComponents() - { - panelGeral.setBorder( BorderFactory.createTitledBorder( "Legisla" + ccedil + atilde + "o de aplica" + ccedil + atilde + "o geral" ) ); - - panelCategorias.setBorder( BorderFactory.createTitledBorder( "Legisla" + ccedil + atilde + "o espec" + iacute + "fica" ) ); - panelButtonsCategoriasCategoria.setBorder( BorderFactory.createTitledBorder( "Categoria" ) ); - panelButtonsCategoriasLegislacao.setBorder( BorderFactory.createTitledBorder( "Legisla" + ccedil + atilde + "o" ) ); - - treeCategorias.setRootVisible( false ); - treeGeral.setRootVisible( false ); - treeCategorias.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - treeGeral.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void startupLayout() - { - LayoutManager layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.FILL - }, new double[] { - TableLayout.FILL, TableLayout.FILL - } ); - this.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - panelGeral.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - panelCategorias.setLayout( layout ); - - layout = new GridLayout( 1, 2, 5, 5 ); - panelButtonsGeral.setLayout( layout ); - - layout = new GridLayout( 1, 4, 5, 5 ); - panelButtonsCategoriasCategoria.setLayout( layout ); - - layout = new GridLayout( 1, 4, 5, 5 ); - panelButtonsCategoriasLegislacao.setLayout( layout ); - } - - private void placeComponents() - { - panelButtonsGeral.add( buttonGeralCriar ); - panelButtonsGeral.add( buttonGeralRemover ); - - panelButtonsCategoriasCategoria.add( buttonCategoriaCriar ); - panelButtonsCategoriasCategoria.add( buttonCategoriaEditar ); - panelButtonsCategoriasCategoria.add( buttonCategoriaRemover ); - panelButtonsCategoriasCategoria.add( new JPanel() ); - - panelButtonsCategoriasLegislacao.add( buttonCategoriasLegislacaoCriar ); - panelButtonsCategoriasLegislacao.add( buttonCategoriasLegislacaoRemover ); - panelButtonsCategoriasLegislacao.add( new JPanel() ); - panelButtonsCategoriasLegislacao.add( new JPanel() ); - - panelGeral.add( panelButtonsGeral, new TableLayoutConstraints( 0, 0 ) ); - panelGeral.add( scrollGeral, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - - panelCategorias.add( panelButtonsCategoriasCategoria, new TableLayoutConstraints( 0, 0 ) ); - panelCategorias.add( panelButtonsCategoriasLegislacao, new TableLayoutConstraints( 1, 0 ) ); - panelCategorias.add( scrollCategorias, new TableLayoutConstraints( 0, 1, 2, 1 ) ); - - this.add( panelGeral, new TableLayoutConstraints( 0, 0 ) ); - this.add( panelCategorias, new TableLayoutConstraints( 0, 1 ) ); - this.add( panelData, new TableLayoutConstraints( 1, 0, 1, 1 ) ); - } - - private void setupListeners() - { - treeCategorias.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath selectionPath = e.getNewLeadSelectionPath(); - if( selectionPath != null ) - { - Object last = selectionPath.getLastPathComponent(); - if( last instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode) last).getUserObject(); - if( userObject instanceof HsLegislacaoData ) - { - selectedLegislacaoEspecifica = (HsLegislacaoData) userObject; - } - else if( userObject instanceof HsLegislacaoCategoriaData ) - { - selectedCategoria = (HsLegislacaoCategoriaData) userObject; - } - } - treeGeral.clearSelection(); - selectedLegislacaoGeral = null; - } - else - { - selectedLegislacaoEspecifica = null; - selectedCategoria = null; - } - refreshData(); - setEnable(); - } - } ); - treeGeral.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath selectionPath = e.getNewLeadSelectionPath(); - if( selectionPath != null ) - { - Object last = selectionPath.getLastPathComponent(); - if( last instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode) last).getUserObject(); - if( userObject instanceof HsLegislacaoData ) - { - selectedLegislacaoGeral = (HsLegislacaoData) userObject; - } - } - treeCategorias.clearSelection(); - selectedLegislacaoEspecifica = null; - selectedCategoria = null; - } - else - { - selectedLegislacaoGeral = null; - } - refreshData(); - setEnable(); - } - } ); - panelData.addPropertyChangeListener( LeafTextAreaEditor.ACTION_SAVE, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - try - { - String newValue = (String) evt.getNewValue(); - if( selectedLegislacaoEspecifica != null ) - { - selectedLegislacaoEspecifica.setDescription( newValue ); - selectedLegislacaoEspecifica.save(); - } - else if( selectedLegislacaoGeral != null ) - { - selectedLegislacaoGeral.setDescription( newValue ); - selectedLegislacaoGeral.save(); - } - doRefresh(); - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - } ); - buttonCategoriaCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarCategoria(); - } - } ); - buttonCategoriaEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarCategoria(); - } - } ); - buttonCategoriaRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerCategoria(); - } - } ); - buttonCategoriasLegislacaoCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarCategoriaLegislacao(); - } - } ); - buttonCategoriasLegislacaoRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerCategoriaLegislacao(); - } - } ); - buttonGeralCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarGeral(); - } - } ); - buttonGeralRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerGeral(); - } - } ); - } - - private void criarCategoria() - { - try - { - String categoriaString = JOptionPane.showInputDialog( this, "Nova categoria", "" ); - if( categoriaString != null ) - { - HsLegislacaoCategoriaData novaCategoria = new HsLegislacaoCategoriaData(); - novaCategoria.setDescription( categoriaString ); - novaCategoria.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarCategoria() - { - try - { - if( selectedCategoria != null ) - { - String categoriaString = JOptionPane.showInputDialog( this, "Nova categoria", selectedCategoria.getDescription() ); - if( categoriaString != null ) - { - selectedCategoria.setDescription( categoriaString ); - selectedCategoria.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerCategoria() - { - try - { - if( selectedCategoria != null && LeafDialog.confirmDelete( false, false, "categoria" ) ) - { - selectedCategoria.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - selectedCategoria.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void criarCategoriaLegislacao() - { - try - { - if( selectedCategoria != null ) - { - HsLegislacaoData novaLegislacao = new HsLegislacaoData(); - novaLegislacao.setDescription( "" ); - novaLegislacao.setToCategoria_id( selectedCategoria ); - novaLegislacao.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerCategoriaLegislacao() - { - try - { - if( selectedLegislacaoEspecifica != null && LeafDialog.confirmDelete( false, false, "legisla" + ccedil + atilde + "o" ) ) - { - selectedLegislacaoEspecifica.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - selectedLegislacaoEspecifica.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerGeral() - { - try - { - if( selectedLegislacaoGeral != null && LeafDialog.confirmDelete( false, false, "legisla" + ccedil + atilde + "o" ) ) - { - selectedLegislacaoGeral.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - selectedLegislacaoGeral.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void criarGeral() - { - try - { - HsLegislacaoData legislacao = new HsLegislacaoData(); - legislacao.setDescription( "" ); - legislacao.save(); - doRefresh(); - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - @Override - public void refresh() - { - rootGeral.removeAllChildren(); - rootCategorias.removeAllChildren(); - TreeTools.merge( rootGeral, HigieneSegurancaLogic.getLegislacaoGeral() ); - TreeTools.merge( rootCategorias, HigieneSegurancaLogic.getLegislacaoEspecifica() ); - TreeTools.refreshTree( treeGeral, rootGeral, false ); - TreeTools.refreshTree( treeCategorias, rootCategorias, false ); - setEnable(); - } - - private void refreshData() - { - buttonCategoriaEditar.setEnabled( false ); - buttonCategoriaRemover.setEnabled( false ); - buttonCategoriasLegislacaoCriar.setEnabled( false ); - buttonCategoriasLegislacaoRemover.setEnabled( false ); - buttonGeralRemover.setEnabled( false ); - panelData.setEnabled( false ); - if( selectedLegislacaoEspecifica != null ) - { - panelData.setValue( selectedLegislacaoEspecifica.getDescription() ); - panelData.setEnabled( true ); - } - else if( selectedLegislacaoGeral != null ) - { - panelData.setValue( selectedLegislacaoGeral.getDescription() ); - panelData.setEnabled( true ); - } - else - { - panelData.setValue( null ); - } - if( selectedCategoria != null ) - { - buttonCategoriaEditar.setEnabled( true ); - buttonCategoriaRemover.setEnabled( true ); - } - } - - private void setEnable() - { - buttonCategoriaEditar.setEnabled( selectedCategoria != null ); - buttonCategoriaRemover.setEnabled( selectedCategoria != null ); - buttonCategoriasLegislacaoCriar.setEnabled( selectedCategoria != null ); - buttonCategoriasLegislacaoRemover.setEnabled( selectedLegislacaoEspecifica != null ); - buttonGeralRemover.setEnabled( selectedLegislacaoGeral != null ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/AdicionarNormalizacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/AdicionarNormalizacaoPanel.java deleted file mode 100644 index 88928723..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/AdicionarNormalizacaoPanel.java +++ /dev/null @@ -1,209 +0,0 @@ -package siprp.higiene.gestao.normalizacao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import leaf.ui.LeafDialog; -import leaf.ui.TreeInserterDialog; -import shst.data.outer.EmpresasData; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsNormalizacaoData; -import shst.data.outer.HsNormalizacaoEmpresaData; -import shst.data.outer.HsNormalizacaoEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.AdicionarPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarNormalizacaoPanel extends AdicionarPanel -{ - - private static final long serialVersionUID = 1L; - - private EmpresasData empresa = null; - - private EstabelecimentosData estabelecimento = null; - - public void setEmpresa( EmpresasData empresa ) - { - this.empresa = empresa; - this.estabelecimento = null; - doRefresh(); - setEnabled(); - } - - public void setEstabelecimento( EstabelecimentosData estabelecimento ) - { - this.empresa = null; - this.estabelecimento = estabelecimento; - doRefresh(); - setEnabled(); - } - - @Override - protected void add() - { - DefaultMutableTreeNode allNormalizacao = getAllNormalizacao(); - removeCurrent( allNormalizacao ); - TreeInserterDialog dialog = new TreeInserterDialog( "Adicionar Normaliza" + ccedil + atilde + "o", allNormalizacao ); - DefaultMutableTreeNode result = dialog.getResult(); - if( result != null ) - { - addResult( result ); - doRefresh(); - } - setEnabled(); - } - - private DefaultMutableTreeNode getAllNormalizacao() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - if( empresa != null ) - { - result = HigieneSegurancaLogic.getNormalizacaoTreeForEmpresa( null ); - } - else if( estabelecimento != null ) - { - result = HigieneSegurancaLogic.getNormalizacaoTreeForEmpresa( estabelecimento.toEmpresa_id() ); - } - return result; - } - - private void removeCurrent( DefaultMutableTreeNode all ) - { - if( all != null && root.getChildCount() == 2 && all.getChildCount() == 2 ) - { - DefaultMutableTreeNode portuguesaAll = (DefaultMutableTreeNode) all.getChildAt( 0 ); - DefaultMutableTreeNode internacionalAll = (DefaultMutableTreeNode) all.getChildAt( 1 ); - DefaultMutableTreeNode portuguesaCurrent = (DefaultMutableTreeNode) root.getChildAt( 0 ); - DefaultMutableTreeNode internacionalCurrent = (DefaultMutableTreeNode) root.getChildAt( 1 ); - TreeTools.remove( portuguesaAll, portuguesaCurrent ); - TreeTools.remove( internacionalAll, internacionalCurrent ); - } - setEnabled(); - } - - private void addResult( DefaultMutableTreeNode root ) - { - try - { - if( root != null ) - { - Object userObject = root.getUserObject(); - if( userObject instanceof HsNormalizacaoData ) - { - if( empresa != null ) - { - HsNormalizacaoEmpresaData rel = new HsNormalizacaoEmpresaData(); - rel.setToEmpresa_id( empresa ); - rel.setToNormalizacao_id( ((HsNormalizacaoData) userObject ) ); - rel.save(); - } - else if( estabelecimento != null ) - { - HsNormalizacaoEstabelecimentoData rel = new HsNormalizacaoEstabelecimentoData(); - rel.setToEstabelecimento_id( estabelecimento ); - rel.setToNormalizacao_id( ((HsNormalizacaoData) userObject ) ); - rel.save(); - } - } - } - for( int i = 0; i < root.getChildCount(); ++i ) - { - DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt( i ); - addResult( child ); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - @Override - public void refresh() - { - root.removeAllChildren(); - if( empresa != null) - { - TreeTools.merge( root, HigieneSegurancaLogic.getNormalizacaoTreeForEmpresa( empresa ) ); - } - if( estabelecimento != null ) - { - TreeTools.merge( root, HigieneSegurancaLogic.getNormalizacaoTreeForEstabelecimento( estabelecimento ) ); - } - TreeTools.refreshTree( tree, root, false ); - } - - @Override - protected void setEnabled() - { - buttonAdicionar.setEnabled( empresa != null || estabelecimento != null ); - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - - @Override - protected void rem() - { - try - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - Object obj = node.getUserObject(); - if( obj != null && (obj instanceof HsNormalizacaoData) ) - { - if( empresa != null ) - { - removeFromEmpresa( ((HsNormalizacaoData) obj ) ); - } - else if( estabelecimento != null ) - { - removeFromEstabelecimento( ((HsNormalizacaoData) obj )); - } - doRefresh(); - } - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removeFromEmpresa( HsNormalizacaoData normalizacao ) throws Exception - { - if( normalizacao != null && empresa != null && LeafDialog.confirmDelete( false, false, "normaliza" + ccedil + atilde + "o" ) ) - { - for( HsNormalizacaoEmpresaData rel : empresa.fromHsNormalizacaoEmpresa_empresa_id() ) - { - if( normalizacao.equals( rel.toNormalizacao_id() ) ) - { - rel.delete(); - break; - } - } - } - } - - private void removeFromEstabelecimento( HsNormalizacaoData normalizacao ) throws Exception - { - if( normalizacao != null && estabelecimento != null && LeafDialog.confirmDelete( false, false, "normaliza" + ccedil + atilde + "o" ) ) - { - for( HsNormalizacaoEstabelecimentoData rel : estabelecimento.fromHsNormalizacaoEstabelecimento_estabelecimento_id() ) - { - if( normalizacao.equals( rel.toNormalizacao_id() ) ) - { - rel.delete(); - break; - } - } - - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/GerirNormalizacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/GerirNormalizacaoPanel.java deleted file mode 100644 index c14441f8..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/normalizacao/GerirNormalizacaoPanel.java +++ /dev/null @@ -1,555 +0,0 @@ -package siprp.higiene.gestao.normalizacao; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.GridLayout; -import java.awt.LayoutManager; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Date; - -import javax.swing.BorderFactory; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.LeafUIConstants; -import shst.data.outer.HsNormalizacaoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.SIPRPSpellChecker; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirNormalizacaoPanel extends SIPRPLazyLoadedPanel implements LeafUIConstants, CaretListener -{ - - private static final long serialVersionUID = 1L; - - private final JPanel panelPortuguesa = new JPanel(); - - private final JPanel panelInternacional = new JPanel(); - - private final JPanel panelButtonsPortuguesa = new JPanel(); - - private final LeafButton buttonPortuguesaCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonPortuguesaEditar = LeafIconButton.createDefaultEditButton(); - - private final LeafButton buttonPortuguesaRemover = LeafIconButton.createDefaultRemoveButton(); - - private final JPanel panelButtonsInternacional = new JPanel(); - - private final LeafButton buttonInternacionalCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonInternacionalEditar = LeafIconButton.createDefaultEditButton(); - - private final LeafButton buttonInternacionalRemover = LeafIconButton.createDefaultRemoveButton(); - - private final LeafButton buttonSave = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private final LeafButton buttonRevert = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final DefaultMutableTreeNode rootPortuguesa = new DefaultMutableTreeNode(); - - private final DefaultTreeModel modelPortuguesa = new DefaultTreeModel( rootPortuguesa ); - - private final LeafTree treePortuguesa = new LeafTree( modelPortuguesa ); - - private final JScrollPane scrollPortuguesa = new JScrollPane( treePortuguesa ); - - private final DefaultMutableTreeNode rootInternacional = new DefaultMutableTreeNode(); - - private final DefaultTreeModel modelInternacional = new DefaultTreeModel( rootInternacional ); - - private final LeafTree treeInternacional = new LeafTree( modelInternacional ); - - private final JScrollPane scrollInternacional = new JScrollPane( treeInternacional ); - - private HsNormalizacaoData selectedPortuguesa = null; - - private HsNormalizacaoData selectedInternacional = null; - - private final JPanel panelData = new JPanel(); - - private final JTextField textCodigo = new JTextField(10); - - private final JTextArea textAreaDescricao = new JTextArea(); - - public GerirNormalizacaoPanel() - { - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void startupComponents() - { - panelPortuguesa.setBorder( BorderFactory.createTitledBorder( "Normaliza" + ccedil + atilde + "o Portuguesa" ) ); - - panelInternacional.setBorder( BorderFactory.createTitledBorder( "Normaliza" + ccedil + atilde + "o Internacional" ) ); - - treeInternacional.setRootVisible( false ); - treePortuguesa.setRootVisible( false ); - treeInternacional.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - treePortuguesa.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - - textCodigo.setEnabled( false ); - - buttonSave.setEnabled( false ); - buttonRevert.setEnabled( false ); - } - - private void startupLayout() - { - LayoutManager layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.FILL - }, new double[] { - TableLayout.FILL, TableLayout.FILL - } ); - this.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - panelPortuguesa.setLayout( layout ); - ((TableLayout) layout).setHGap( 5 ); - ((TableLayout) layout).setVGap( 5 ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - ((TableLayout) layout).setHGap( 5 ); - ((TableLayout) layout).setVGap( 5 ); - - panelInternacional.setLayout( layout ); - - layout = new GridLayout( 1, 3, 5, 5 ); - panelButtonsPortuguesa.setLayout( layout ); - - layout = new GridLayout( 1, 3, 5, 5 ); - panelButtonsInternacional.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - } ); - ((TableLayout) layout).setHGap( 5 ); - ((TableLayout) layout).setVGap( 5 ); - panelData.setLayout( layout ); - } - - private void placeComponents() - { - panelButtonsPortuguesa.add( buttonPortuguesaCriar ); - panelButtonsPortuguesa.add( buttonPortuguesaEditar ); - panelButtonsPortuguesa.add( buttonPortuguesaRemover ); - - panelButtonsInternacional.add( buttonInternacionalCriar ); - panelButtonsInternacional.add( buttonInternacionalEditar ); - panelButtonsInternacional.add( buttonInternacionalRemover ); - - panelPortuguesa.add( panelButtonsPortuguesa, new TableLayoutConstraints( 0, 0 ) ); - panelPortuguesa.add( scrollPortuguesa, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - - panelInternacional.add( panelButtonsInternacional, new TableLayoutConstraints( 0, 0 ) ); - panelInternacional.add( scrollInternacional, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - - panelData.add( buttonSave, new TableLayoutConstraints( 3, 0 ) ); - panelData.add( buttonRevert, new TableLayoutConstraints( 4, 0 ) ); - panelData.add( new JLabel("C" + oacute + "digo"), new TableLayoutConstraints( 0, 1 ) ); - panelData.add( textCodigo, new TableLayoutConstraints( 1, 1 ) ); - panelData.add( textAreaDescricao, new TableLayoutConstraints( 0, 2, 4, 2 ) ); - - this.add( panelPortuguesa, new TableLayoutConstraints( 0, 0 ) ); - this.add( panelInternacional, new TableLayoutConstraints( 0, 1 ) ); - this.add( panelData, new TableLayoutConstraints( 1, 0, 1, 1 ) ); - } - - private void setupListeners() - { - treeInternacional.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath selectionPath = e.getNewLeadSelectionPath(); - if( selectionPath != null ) - { - Object last = selectionPath.getLastPathComponent(); - if( last instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode) last).getUserObject(); - if( userObject instanceof HsNormalizacaoData ) - { - selectedInternacional = (HsNormalizacaoData) userObject; - } - } - treePortuguesa.clearSelection(); - selectedPortuguesa = null; - } - else - { - selectedInternacional = null; - } - refreshData(); - setEnable(); - } - } ); - treePortuguesa.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath selectionPath = e.getNewLeadSelectionPath(); - if( selectionPath != null ) - { - Object last = selectionPath.getLastPathComponent(); - if( last instanceof DefaultMutableTreeNode ) - { - Object userObject = ((DefaultMutableTreeNode) last).getUserObject(); - if( userObject instanceof HsNormalizacaoData ) - { - selectedPortuguesa = (HsNormalizacaoData) userObject; - } - } - treeInternacional.clearSelection(); - selectedInternacional = null; - } - else - { - selectedPortuguesa = null; - } - refreshData(); - setEnable(); - } - } ); - textCodigo.addCaretListener( this ); - textAreaDescricao.addCaretListener( this ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( textAreaDescricao ); - buttonPortuguesaCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarPortuguesa(); - } - } ); - buttonPortuguesaEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarPortuguesa(); - } - } ); - buttonPortuguesaRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerPortuguesa(); - } - } ); - buttonInternacionalCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarInternacional(); - } - } ); - buttonInternacionalEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarInternacional(); - } - } ); - buttonInternacionalRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerInternacional(); - } - } ); - buttonSave.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - try - { - save(); - } catch( Exception e1 ) - { - LeafDialog.error( e1 ); - } - } - } ); - buttonRevert.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - if( selectedInternacional != null ) - { - textAreaDescricao.setText( selectedInternacional.getDescricao() ); - textAreaDescricao.setEnabled( true ); - textCodigo.setText( selectedInternacional.getCodigo() ); - } - else if( selectedPortuguesa != null ) - { - textAreaDescricao.setText( selectedPortuguesa.getDescricao() ); - textAreaDescricao.setEnabled( true ); - textCodigo.setText( selectedPortuguesa.getCodigo() ); - } - else - { - textAreaDescricao.setText( "" ); - textCodigo.setText( "" ); - } - } - } ); - } - - private void save() throws Exception - { - if( selectedInternacional != null ) - { - selectedInternacional.setCodigo( textCodigo.getText() ); - selectedInternacional.setDescricao( textAreaDescricao.getText() ); - selectedInternacional.save(); - } - else if( selectedPortuguesa != null ) - { - selectedPortuguesa.setCodigo( textCodigo.getText() ); - selectedPortuguesa.setDescricao( textAreaDescricao.getText() ); - selectedPortuguesa.save(); - } - doRefresh(); - } - - private String getCodigoForNormalizacao( boolean criar, boolean portuguesa ) - { - String result = null; - if( criar ) - { - result = JOptionPane.showInputDialog( this, "C" + oacute + "digo", "Criar normaliza" + ccedil + atilde + "o" + (portuguesa ? " Portuguesa": " internacional"), JOptionPane.QUESTION_MESSAGE ); - } - else - { - result = JOptionPane.showInputDialog( this, "C" + oacute + "digo", portuguesa ? selectedPortuguesa.getCodigo() : selectedInternacional.getCodigo() ); - } - return result; - } - - private boolean isValidCodigo( String codigo ) - { - boolean result = false; - if( codigo != null ) - { - result = true; - } - return result; - } - - private void criarPortuguesa() - { - try - { - String codigo = getCodigoForNormalizacao(true,true); - if( isValidCodigo(codigo) ) - { - HsNormalizacaoData normalizacao = new HsNormalizacaoData(); - normalizacao.setDescricao( "" ); - normalizacao.setCodigo( codigo ); - normalizacao.setPortuguesa( true ); - normalizacao.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarPortuguesa() - { - try - { - if( selectedPortuguesa != null ) - { - String codigo = getCodigoForNormalizacao(false, true); - if( isValidCodigo(codigo) ) - { - selectedPortuguesa.setCodigo( codigo ); - selectedPortuguesa.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerPortuguesa() - { - try - { - if( selectedPortuguesa != null && LeafDialog.confirmDelete( false, false, "normaliza" + ccedil + atilde + "o" ) ) - { - selectedPortuguesa.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - selectedPortuguesa.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void criarInternacional() - { - try - { - String codigo = getCodigoForNormalizacao(true, false); - if( isValidCodigo(codigo) ) - { - HsNormalizacaoData normalizacao = new HsNormalizacaoData(); - normalizacao.setDescricao( "" ); - normalizacao.setCodigo( codigo ); - normalizacao.setPortuguesa( false ); - normalizacao.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarInternacional() - { - try - { - if( selectedInternacional != null ) - { - String codigo = getCodigoForNormalizacao(false, false); - if( isValidCodigo(codigo) ) - { - selectedInternacional.setCodigo( codigo ); - selectedInternacional.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerInternacional() - { - try - { - if( selectedInternacional != null && LeafDialog.confirmDelete( false, false, "normaliza" + ccedil + atilde + "o" ) ) - { - selectedInternacional.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - selectedInternacional.save(); - doRefresh(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - @Override - public void refresh() - { - rootPortuguesa.removeAllChildren(); - rootInternacional.removeAllChildren(); - textCodigo.setText( "" ); - TreeTools.merge( rootPortuguesa, HigieneSegurancaLogic.getNormalizacaoTree( true ) ); - TreeTools.merge( rootInternacional, HigieneSegurancaLogic.getNormalizacaoTree( false ) ); - TreeTools.refreshTree( treePortuguesa, rootPortuguesa, false ); - TreeTools.refreshTree( treeInternacional, rootInternacional, false ); - setEnable(); - } - - private void refreshData() - { - buttonInternacionalRemover.setEnabled( false ); - buttonPortuguesaRemover.setEnabled( false ); - buttonInternacionalEditar.setEnabled( false ); - buttonPortuguesaEditar.setEnabled( false ); - textAreaDescricao.setEnabled( false ); - buttonSave.setEnabled( false ); - buttonRevert.setEnabled( false ); - if( selectedInternacional != null ) - { - textAreaDescricao.setText( selectedInternacional.getDescricao() ); - textAreaDescricao.setEnabled( true ); - textCodigo.setText( selectedInternacional.getCodigo() ); - textCodigo.setEnabled( true ); - } - else if( selectedPortuguesa != null ) - { - textAreaDescricao.setText( selectedPortuguesa.getDescricao() ); - textAreaDescricao.setEnabled( true ); - textCodigo.setText( selectedPortuguesa.getCodigo() ); - textCodigo.setEnabled( true ); - } - else - { - textAreaDescricao.setText( "" ); - textCodigo.setText( "" ); - } - } - - private void setEnable() - { - buttonPortuguesaEditar.setEnabled( selectedPortuguesa != null ); - buttonPortuguesaRemover.setEnabled( selectedPortuguesa != null ); - buttonInternacionalEditar.setEnabled( selectedInternacional != null ); - buttonInternacionalRemover.setEnabled( selectedInternacional != null ); - } - - @Override - public void caretUpdate( CaretEvent e ) - { - buttonSave.setEnabled( true ); - buttonRevert.setEnabled( true ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/AdicionarAreasPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/AdicionarAreasPanel.java deleted file mode 100644 index 14249169..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/AdicionarAreasPanel.java +++ /dev/null @@ -1,240 +0,0 @@ -package siprp.higiene.gestao.postos; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.TreeInserterDialog; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsPostoData; -import shst.data.outer.HsPostoEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; -import shst.logic.node.AreaNode; -import shst.logic.node.PostoNode; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarAreasPanel extends JPanel -{ - - private static final long serialVersionUID = 1L; - - public static final String SELECTION_CHANGED = "SELECTION_CHANGED"; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png"; - - protected final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE ); - - protected final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private EstabelecimentosData estabelecimento = null; - - public AdicionarAreasPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonAdicionar.setEnabled( false ); - buttonRemover.setEnabled( false ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1 ) ); - } - - private void startupListeners() - { - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - TreePath path = tree.getSelectionPath(); - Object object = path == null ? null : path.getLastPathComponent(); - HsPostoData posto = object == null ? null : ((object instanceof PostoNode) ? (HsPostoData) ((PostoNode) object).getUserObject() : null); - firePropertyChange( SELECTION_CHANGED, null, posto ); - } - } ); - buttonAdicionar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - add(); - } - } ); - buttonRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - rem(); - } - } ); - } - - private void add() - { - DefaultMutableTreeNode allPostos = HigieneSegurancaLogic.getAreasTree( estabelecimento.toEmpresa_id() ); - TreeTools.removeAll( allPostos, HigieneSegurancaLogic.getPostosTree( estabelecimento ) ); - TreeInserterDialog dialog = new TreeInserterDialog( "Adicionar Postos de Trabalho", allPostos ); - save( dialog.getResult() ); - refresh(); - } - - private void save( DefaultMutableTreeNode toadd ) - { - try - { - Object obj = toadd.getUserObject(); - if( obj instanceof HsPostoData ) - { - HsPostoEstabelecimentoData rel = new HsPostoEstabelecimentoData(); - rel.setToEstabelecimento_id( estabelecimento ); - rel.setToPosto_id( (HsPostoData) obj ); - rel.save(); - } - else - { - for( int i = 0; i < toadd.getChildCount(); ++i ) - { - save( (DefaultMutableTreeNode) toadd.getChildAt( i ) ); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void rem() - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object object = path.getLastPathComponent(); - if( ( object instanceof PostoNode ) && LeafDialog.confirmDelete( true, false, "posto" ) ) - { - HsPostoData posto = ((HsPostoData) ((PostoNode) object).getUserObject()); - remPosto( posto ); - } - else if( ( object instanceof AreaNode ) && LeafDialog.confirmDelete( false, false, aacute + "rea" ) ) - { - for( int i = 0; i < ((AreaNode) object).getChildCount(); ++i ) - { - PostoNode postoNode = (PostoNode) ((AreaNode) object).getChildAt( i ); - remPosto( (HsPostoData) postoNode.getUserObject() ); - } - } - } - refresh(); - } - - private void remPosto( HsPostoData posto ) - { - try - { - HsPostoEstabelecimentoData toDelete = null; - for( HsPostoEstabelecimentoData rel : posto.fromHsPostoEstabelecimento_posto_id() ) - { - if( rel.toEstabelecimento_id().equals( estabelecimento ) ) - { - toDelete = rel; - break; - } - } - if( toDelete != null ) - { - toDelete.delete(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void setEnabled() - { - buttonAdicionar.setEnabled( estabelecimento != null ); - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - - public void refresh() - { - root.removeAllChildren(); - if( estabelecimento != null ) - { - TreeTools.merge( root, HigieneSegurancaLogic.getAreasTree( estabelecimento ) ); - } - setEnabled(); - TreeTools.refreshTree( tree, root, false ); - } - - public void setEstabelecimento( EstabelecimentosData estabelecimento ) - { - this.estabelecimento = estabelecimento; - refresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/GerirAreasPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/GerirAreasPanel.java deleted file mode 100644 index f5a4e6f0..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/postos/GerirAreasPanel.java +++ /dev/null @@ -1,465 +0,0 @@ -package siprp.higiene.gestao.postos; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.eacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.LeafUIConstants; -import shst.data.outer.EmpresasData; -import shst.data.outer.HsAreaData; -import shst.data.outer.HsPostoData; -import shst.logic.node.AreaNode; -import shst.logic.node.PostoNode; - -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirAreasPanel extends JPanel implements LeafUIConstants -{ - - private static final long serialVersionUID = 1L; - - private final JPanel panelButtons = new JPanel(); - - private final JPanel panelTree = new JPanel(); - - public final LeafButton buttonAreaCriar = LeafIconButton.createDefaultNewButton(); - - public final LeafButton buttonAreaEditar = LeafIconButton.createDefaultEditButton(); - - public final LeafButton buttonAreaRemover = LeafIconButton.createDefaultRemoveButton(); - - public final LeafButton buttonPostoCriar = LeafIconButton.createDefaultNewButton(); - - public final LeafButton buttonPostoEditar = LeafIconButton.createDefaultEditButton(); - - public final LeafButton buttonPostoRemover = LeafIconButton.createDefaultRemoveButton(); - - private final JCheckBox checkGenerico = new JCheckBox( "Gen"+eacute+"rico" ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private EmpresasData empresa = null; - - public GerirAreasPanel() - { - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void startupComponents() - { - panelButtons.setPreferredSize( new Dimension( 150, 0 ) ); - panelTree.setPreferredSize( new Dimension( 300, 0 ) ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelButtons.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelTree.setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - panel.setBorder( BorderFactory.createTitledBorder( "Area" ) ); - panel.setLayout( new GridLayout( 1, 3 ) ); - panel.add( buttonAreaCriar ); - panel.add( buttonAreaEditar ); - panel.add( buttonAreaRemover ); - panelButtons.add( panel, new TableLayoutConstraints( 0, 0 ) ); - - panel = new JPanel(); - panel.setBorder( BorderFactory.createTitledBorder( "Posto" ) ); - panel.setLayout( new GridLayout( 1, 3 ) ); - panel.add( buttonPostoCriar ); - panel.add( buttonPostoEditar ); - panel.add( buttonPostoRemover ); - panelButtons.add( panel, new TableLayoutConstraints( 1, 0 ) ); - - panelButtons.add( checkGenerico, new TableLayoutConstraints(2,0)); - - panelTree.add( scroll, new TableLayoutConstraints( 0, 0 ) ); - - add( panelButtons, new TableLayoutConstraints( 0, 0 ) ); - add( panelTree, new TableLayoutConstraints( 0, 1 ) ); - } - - private void setupListeners() - { - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setSelected(); - } - } ); - buttonAreaCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarArea(); - } - } ); - buttonAreaEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarArea(); - } - } ); - buttonAreaRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerArea(); - } - } ); - buttonPostoCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarPosto(); - } - } ); - buttonPostoEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarPosto(); - } - } ); - buttonPostoRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerPosto(); - } - } ); - checkGenerico.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - HsPostoData posto = getSelectedPosto(); - if( posto != null ) - { - posto.setIs_principal( checkGenerico.isSelected() ); - try - { - posto.save(); - } catch( Exception e1 ) - { - e1.printStackTrace(); - } - } - } - } ); - } - - private void criarArea() - { - try - { - if( empresa != null ) - { - String areaString = JOptionPane.showInputDialog( this, "Descri" + ccedil + atilde + "o", "Criar nova " + aacute + "rea", JOptionPane.QUESTION_MESSAGE ); - if( areaString != null ) - { - HsAreaData area = new HsAreaData(); - area.setToEmpresa_id( empresa ); - area.setDescription( areaString ); - area.save(); - refresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarArea() - { - try - { - HsAreaData area = getSelectedArea(); - if( area != null ) - { - String areaString = JOptionPane.showInputDialog( this, "Descri" + ccedil + atilde + "o", area.getDescription() ); - if( areaString != null ) - { - area.setDescription( areaString ); - area.save(); - refresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerArea() - { - HsAreaData area = getSelectedArea(); - if( area != null ) - { - List< HsPostoData > listPostos = area.fromHsPosto_area_id(); - if ( listPostos != null && listPostos.size() > 0 ) - { - JOptionPane.showMessageDialog( this, "Tem de remover todos os postos primeiro.", "Erro", JOptionPane.ERROR_MESSAGE ); - } - else if ( LeafDialog.confirmDelete( false, false, aacute + "rea") ) - { - try - { - area.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - area.save(); -// area.delete(); - refresh(); - } - catch ( Exception e ) - { - LeafDialog.error( e ); - } - } - } - } - - private void criarPosto() - { - try - { - HsAreaData area = getSelectedArea(); - if( area != null ) - { - String postoString = JOptionPane.showInputDialog( this, "Descri" + ccedil + atilde + "o", "Criar novo posto de trabalho", JOptionPane.QUESTION_MESSAGE ); - if( postoString != null ) - { - HsPostoData posto = new HsPostoData(); - posto.setToArea_id( area ); - posto.setDescription( postoString ); - posto.save(); - refresh(); - } - refresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarPosto() - { - try - { - HsPostoData posto = getSelectedPosto(); - if( posto != null ) - { - String postoString = JOptionPane.showInputDialog( this, "Descri" + ccedil + atilde + "o", posto.getDescription() ); - if( postoString != null ) - { - posto.setDescription( postoString ); - posto.save(); - refresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerPosto() - { - try - { - HsPostoData posto = getSelectedPosto(); - if( posto != null && LeafDialog.confirmDelete( true, false, "posto" ) ) - { - posto.setDeleted_date( new java.sql.Timestamp( new Date().getTime() ) ); - posto.save(); - refresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private HsAreaData getSelectedArea() - { - HsAreaData result = null; - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object leaf = path.getLastPathComponent(); - if( leaf != null ) - { - if( leaf instanceof AreaNode ) - { - result = (HsAreaData) ((AreaNode) leaf).getUserObject(); - } - else if( leaf instanceof PostoNode ) - { - result = (HsAreaData) ((HsPostoData) ((PostoNode) leaf).getUserObject()).toArea_id(); - } - } - } - return result; - } - - private HsPostoData getSelectedPosto() - { - HsPostoData result = null; - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object leaf = path.getLastPathComponent(); - if( leaf != null && (leaf instanceof PostoNode) ) - { - result = (HsPostoData) ((PostoNode) leaf).getUserObject(); - } - } - return result; - } - - private void setSelected() - { - TreePath path = tree.getSelectionPath(); - TreeNode node = path == null ? null : (TreeNode) path.getLastPathComponent(); - boolean areaSelected = node != null && (node instanceof AreaNode); - boolean postoSelected = node != null && (node instanceof PostoNode); - buttonPostoCriar.setEnabled( areaSelected || postoSelected ); - buttonPostoEditar.setEnabled( postoSelected ); - buttonPostoRemover.setEnabled( postoSelected ); - buttonAreaRemover.setEnabled( areaSelected ); - buttonAreaCriar.setEnabled( empresa != null ); - buttonAreaEditar.setEnabled( areaSelected ); - checkGenerico.setEnabled( postoSelected ); - boolean generico = false; - if( postoSelected && node != null) - { - HsPostoData posto = (HsPostoData) ((PostoNode) node).getUserObject(); - generico = posto != null && (posto.getIs_principal() ==null ? false : posto.getIs_principal() ); - } - checkGenerico.setSelected(generico); - } - - public void refresh() - { - root.removeAllChildren(); - if( empresa != null ) - { - List areas = empresa.fromHsArea_empresa_id(); - Collections.sort( areas ); - for( HsAreaData area : areas ) - { - addArea( area ); - } - } - setSelected(); - TreeTools.refreshTree( tree, root, false ); - } - - private void addArea( HsAreaData area ) - { - if( area != null ) - { - AreaNode areaNode = new AreaNode( area ); - for( HsPostoData posto : area.fromHsPosto_area_id() ) - { - addPosto( posto, areaNode ); - } - root.add( areaNode ); - } - } - - private void addPosto( HsPostoData posto, AreaNode areaNode ) - { - if( posto != null && posto.getDeleted_date() == null ) - { - PostoNode postoNode = new PostoNode( posto ); - areaNode.add( postoNode ); - } - } - - public void setEmpresa( EmpresasData empresa ) - { - this.empresa = empresa; - refresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/AdicionarRiscosPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/AdicionarRiscosPanel.java deleted file mode 100644 index abb87718..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/AdicionarRiscosPanel.java +++ /dev/null @@ -1,310 +0,0 @@ -package siprp.higiene.gestao.riscos; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Collections; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.TreeInserterDialog; -import shst.data.object.BaseObject; -import shst.data.outer.EmpresasData; -import shst.data.outer.HsPostoData; -import shst.data.outer.HsPostoRiscoData; -import shst.data.outer.HsRiscoData; -import shst.data.outer.HsRiscoEmpresaData; -import shst.logic.HigieneSegurancaLogic; -import shst.logic.node.NodeRisco; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class AdicionarRiscosPanel extends SIPRPLazyLoadedPanel -{ - - private static final long serialVersionUID = 1L; - - public static final String SELECTION_CHANGED = "RISCOS_SELECTION_CHANGED"; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png"; - - protected final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE ); - - protected final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private EmpresasData empresa = null; - - private HsPostoData posto = null; - - public AdicionarRiscosPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonAdicionar.setEnabled( false ); - buttonRemover.setEnabled( false ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1 ) ); - } - - private void startupListeners() - { - buttonAdicionar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - add(); - } - } ); - buttonRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - rem(); - } - } ); - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object selection = path.getLastPathComponent(); - firePropertyChange( SELECTION_CHANGED, null, selection ); - } - } - } ); - } - - private void add() - { - DefaultMutableTreeNode allRiscos = getAllRiscos(); - TreeTools.removeAll( allRiscos, getRiscosTree() ); - TreeInserterDialog dialog = new TreeInserterDialog( "Adicionar Riscos", allRiscos ); - DefaultMutableTreeNode result = dialog.getResult(); - if( result != null ) - { - addResult( result ); - doRefresh(); - } - setEnabled(); - } - - private DefaultMutableTreeNode getAllRiscos() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - if( posto == null ) - { - result = HigieneSegurancaLogic.getRiscosTree(); - } - else - { - result = HigieneSegurancaLogic.getRiscosTree( posto.toArea_id().toEmpresa_id() ); - } - return result; - } - - private DefaultMutableTreeNode getRiscosTree() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - for( int i = 0; i < root.getChildCount(); ++i ) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) root.getChildAt( i ); - BaseObject userObject = (BaseObject) childNode.getUserObject(); - HsRiscoData risco = null; - if( userObject instanceof HsRiscoEmpresaData ) - { - risco = ((HsRiscoEmpresaData) userObject).toRisco_id(); - } - else if( userObject instanceof HsPostoRiscoData ) - { - risco = ((HsPostoRiscoData) userObject).toRisco_id(); - } - if( risco != null ) - { - result.add( new NodeRisco( risco ) ); - } - } - return result; - } - - private void addResult( DefaultMutableTreeNode root ) - { - try - { - if( root != null ) - { - if( root instanceof NodeRisco ) - { - HsRiscoData risco = (HsRiscoData) root.getUserObject(); - if( empresa != null ) - { - HsRiscoEmpresaData rel = new HsRiscoEmpresaData(); - rel.setToEmpresa_id( empresa ); - rel.setToRisco_id( risco ); - rel.save(); - } - else if( posto != null ) - { - HsPostoRiscoData rel = new HsPostoRiscoData(); - rel.setToPosto_id( posto ); - rel.setToRisco_id( risco ); - rel.save(); - } - } - for( int i = 0; i < root.getChildCount(); ++i ) - { - DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt( i ); - addResult( child ); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void rem() - { - try - { - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); - Object obj = node.getUserObject(); - if( obj != null && LeafDialog.confirmDelete( true, false, "risco" ) ) - { - ((BaseObject) obj).delete(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void setEnabled() - { - if( empresa != null ) - { - buttonAdicionar.setEnabled( true ); - } - else if( posto != null ) - { - buttonAdicionar.setEnabled( true ); - } - else - { - buttonAdicionar.setEnabled( false ); - } - buttonRemover.setEnabled( tree.getSelectionCount() > 0 ); - } - - @Override - public void refresh() - { - root.removeAllChildren(); - if( empresa != null ) - { - List riscos = empresa.fromHsRiscoEmpresa_empresa_id(); - Collections.sort( riscos ); - for( HsRiscoEmpresaData rel : riscos ) - { - root.add( new DefaultMutableTreeNode( rel ) ); - } - } - else if( posto != null ) - { - List riscos = posto.fromHsPostoRisco_posto_id(); - Collections.sort( riscos ); - for( HsPostoRiscoData rel : riscos ) - { - root.add( new DefaultMutableTreeNode( rel ) ); - } - } - setEnabled(); - TreeTools.refreshTree( tree, root, false ); - } - - public void setEmpresa( EmpresasData empresa ) - { - this.empresa = empresa; - this.posto = null; - doRefresh(); - } - - public void setPosto( HsPostoData posto ) - { - this.posto = posto; - this.empresa = null; - doRefresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/DnDRiscosListener.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/DnDRiscosListener.java deleted file mode 100644 index 1c97a9dc..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/DnDRiscosListener.java +++ /dev/null @@ -1,167 +0,0 @@ -package siprp.higiene.gestao.riscos; - -import java.awt.Point; -import java.awt.dnd.DropTargetDragEvent; -import java.awt.dnd.DropTargetDropEvent; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import shst.data.outer.HsRiscoData; -import shst.data.outer.HsRiscoMedidaData; -import shst.data.outer.HsRiscoTemaData; - -import com.evolute.entity.evo.EvoDataException; -import com.evolute.swing.tree.EvoTreeDnDListener; -import com.evolute.utils.error.ErrorLogger; - -public class DnDRiscosListener extends EvoTreeDnDListener -{ - private TreeRiscos tree; - - private boolean drag = true; - - public DnDRiscosListener( TreeRiscos tree ) - { - super( tree ); - this.tree = tree; - } - - - @Override - public void dragEnter( DropTargetDragEvent dtde ) - { - DefaultMutableTreeNode node = ( ( DefaultMutableTreeNode ) tree.getSelectionPath().getParentPath().getLastPathComponent() ); - drag = node.getUserObject() != null; - if ( ! drag ) - { - dtde.rejectDrag(); - } - } - - @Override - public void dragOver( DropTargetDragEvent dtde ) - { - super.dragOver( dtde ); - - Point pt = dtde.getLocation(); - if ( drag ) - { - TreePath sourcePath = tree.getClosestPathForLocation( pt.x, pt.y ); - Object destObject = ( ( DefaultMutableTreeNode ) sourcePath.getLastPathComponent() ).getUserObject(); - - if ( tree.getSelectedMedida() != null && ( destObject instanceof HsRiscoTemaData ) ) - { - tree.expandPath( sourcePath ); - } - } - } - - @Override - public void drop( DropTargetDropEvent dtde ) - { - Point pt = dtde.getLocation(); - TreePath destinationPath = tree.getClosestPathForLocation( pt.x, pt.y ); - - Object destinationComponent = destinationPath.getLastPathComponent(); - System.out.println( destinationPath ); - System.out.println( ); - - if( destinationComponent instanceof DefaultMutableTreeNode ) - { - System.out.println("moving node ..."); - DefaultMutableTreeNode destinationNode = ( DefaultMutableTreeNode ) destinationComponent; - Object destinationObject = destinationNode.getUserObject(); - - TreePath sourcePath = tree.getSelectionPath(); - Object sourceComponent = sourcePath.getLastPathComponent(); - - if( sourceComponent instanceof DefaultMutableTreeNode ) - { - DefaultMutableTreeNode sourceNode = ( DefaultMutableTreeNode ) sourceComponent; - Object sourceObject = sourceNode.getUserObject(); - - if( destinationObject instanceof HsRiscoTemaData ) - { // something -> tema - if ( sourceObject instanceof HsRiscoData ) - { // risco -> tema - System.out.println("\tmove risco -> tema"); - - HsRiscoTemaData destTema = ( HsRiscoTemaData ) destinationObject; - moveRisco( destinationNode, sourceNode, sourceObject, destTema ); - } - } - else if( destinationObject instanceof HsRiscoData ) - { // something -> risco - if ( sourceObject instanceof HsRiscoMedidaData ) - { // medida -> risco - System.out.println("\tmove medida -> risco"); - HsRiscoData destRisco = ( HsRiscoData ) destinationObject; - - moveMedida( destinationNode, sourceNode, sourceObject, destRisco ); - } - else if( sourceObject instanceof HsRiscoData ) - { // risco -> risco ( risco -> tema ) - System.out.println( "\tmove risco -> risco ( risco -> tema )" ); - - destinationComponent = destinationPath.getParentPath().getLastPathComponent(); - destinationNode = ( DefaultMutableTreeNode )destinationComponent; - destinationObject = destinationNode.getUserObject(); - HsRiscoTemaData destTema = ( HsRiscoTemaData ) destinationObject; - - moveRisco( destinationNode, sourceNode, sourceObject, destTema ); - } - } - else if( destinationObject instanceof HsRiscoMedidaData ) - { // something -> medida - if ( sourceObject instanceof HsRiscoMedidaData ) - { // medida -> medida ( medida -> risco ) - System.out.println( "\tmove medida -> medida parent ( risco )" ); - - destinationComponent = destinationPath.getParentPath().getLastPathComponent(); - destinationNode = ( DefaultMutableTreeNode ) destinationComponent; - destinationObject = destinationNode.getUserObject(); - HsRiscoData destRisco = ( HsRiscoData ) destinationObject; - - moveMedida( destinationNode, sourceNode, sourceObject, destRisco ); - } - } - } - } - } - - - private void moveMedida( DefaultMutableTreeNode destinationNode, DefaultMutableTreeNode sourceNode, Object sourceObject, HsRiscoData destRisco ) - { - HsRiscoMedidaData source = ( HsRiscoMedidaData ) sourceObject; - source.setToRisco_id( destRisco ); - - try - { - source.save(); - destinationNode.add( sourceNode ); - tree.updateUI(); - } - catch ( EvoDataException e ) - { - ErrorLogger.logException( e ); - } - } - - private void moveRisco( DefaultMutableTreeNode destinationNode, DefaultMutableTreeNode sourceNode, Object soruceObject, HsRiscoTemaData destTema ) - { - HsRiscoData source = ( HsRiscoData ) soruceObject; - source.setToTema_id( destTema ); - try - { - source.save(); - destinationNode.add( sourceNode ); - tree.updateUI(); - } - catch ( EvoDataException e ) - { - ErrorLogger.logException( e ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirMedidaPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirMedidaPanel.java deleted file mode 100644 index 5a2d3a01..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirMedidaPanel.java +++ /dev/null @@ -1,204 +0,0 @@ -package siprp.higiene.gestao.riscos; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; - -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import shst.data.outer.HsMedidaData; -import siprp.SIPRPSpellChecker; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.images.ImageException; -import com.evolute.utils.images.ImageIconLoader; - -public class GerirMedidaPanel extends SIPRPLazyLoadedPanel -{ - - public static final String MEDIDA_CHANGED = "MEDIDA_CHANGED"; - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_SAVE = "leaf/ui/icons/save.png"; - - private static final String ICON_NAME_REVERT = "leaf/ui/icons/revert.png"; - - private LeafButton buttonSaveRequesito; - - private LeafButton buttonRevertRequesito; - - private final JTextArea fieldTextMedida = new JTextArea(); - - private final JScrollPane scrollMedida = new JScrollPane( fieldTextMedida ); - - private final JTextArea fieldTextRequisitosLegais = new JTextArea(); - - private final JScrollPane scrollRequesitos = new JScrollPane( fieldTextRequisitosLegais ); - - private HsMedidaData medida = null; - - public GerirMedidaPanel() - { - try - { - buttonSaveRequesito = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_SAVE ) ); - buttonRevertRequesito = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_REVERT ) ); - } - catch( ImageException e ) - { - ErrorLogger.logException( e ); - } - catch ( IOException e ) - { - ErrorLogger.logException( e ); - } - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void startupComponents() - { - fieldTextMedida.setWrapStyleWord( true ); - fieldTextMedida.setLineWrap( true ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( fieldTextMedida ); - fieldTextRequisitosLegais.setWrapStyleWord( true ); - fieldTextRequisitosLegais.setLineWrap( true ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( fieldTextRequisitosLegais ); - scrollMedida.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - scrollMedida.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - scrollRequesitos.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - scrollRequesitos.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - } - - private void setupListeners() - { - fieldTextRequisitosLegais.addCaretListener( new CaretListener() - { - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - } ); - fieldTextMedida.addCaretListener( new CaretListener() - { - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - } ); - buttonSaveRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - saveRequesito(); - } - } ); - buttonRevertRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revertRequesito(); - } - } ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - add( new JLabel( "Requisitos legais" ), new TableLayoutConstraints( 0, 0 ) ); - add( buttonSaveRequesito, new TableLayoutConstraints( 1, 0 ) ); - add( buttonRevertRequesito, new TableLayoutConstraints( 2, 0 ) ); - add( scrollRequesitos, new TableLayoutConstraints( 0, 1, 2, 1 ) ); - add( new JLabel( "Medida" ), new TableLayoutConstraints( 0, 2 ) ); - add( scrollMedida, new TableLayoutConstraints( 0, 3, 2, 3 ) ); - } - - private void setEnabled() - { - boolean medidaChanged = false; - boolean requesitoChanged = false; - if( medida != null ) - { - medidaChanged = !fieldTextMedida.getText().equals( medida.getDescription() ); - requesitoChanged = !fieldTextRequisitosLegais.getText().equals( medida.getRequesitos_legais() ); - } - buttonSaveRequesito.setEnabled( requesitoChanged || medidaChanged ); - buttonRevertRequesito.setEnabled( requesitoChanged || medidaChanged ); - } - - private void saveRequesito() - { - try - { - if( medida != null ) - { - medida.setRequesitos_legais( fieldTextRequisitosLegais.getText() ); - medida.setDescription( fieldTextMedida.getText() ); - medida.save(); - doRefresh(); - } - setEnabled(); - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void revertRequesito() - { - if( medida != null ) - { - fieldTextRequisitosLegais.setText( medida.getRequesitos_legais() ); - fieldTextMedida.setText( medida.getDescription() ); - } - setEnabled(); - } - - @Override - public void refresh() - { - firePropertyChange( MEDIDA_CHANGED, null, medida ); - } - - public void setMedida( HsMedidaData medida ) - { - this.medida = medida; - fieldTextMedida.setText( medida == null ? null : medida.getDescription() ); - fieldTextRequisitosLegais.setText( medida == null ? null : medida.getRequesitos_legais() ); - setEnabled(); - } - - public HsMedidaData getMedida() - { - return this.medida; - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirRiscosPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirRiscosPanel.java deleted file mode 100644 index 62194999..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/GerirRiscosPanel.java +++ /dev/null @@ -1,583 +0,0 @@ -package siprp.higiene.gestao.riscos; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.CardLayout; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafUIConstants; -import shst.data.outer.HsMedidaData; -import shst.data.outer.HsRiscoData; -import shst.data.outer.HsRiscoMedidaData; -import shst.data.outer.HsRiscoTemaData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirRiscosPanel extends SIPRPLazyLoadedPanel implements LeafUIConstants -{ - - private static final long serialVersionUID = 1L; - - private static final String PANEL_TEMA = "PANEL_TEMA"; - - private static final String PANEL_RISCO = "PANEL_RISCO"; - - private static final String PANEL_MEDIDA = "PANEL_MEDIDA"; - - private final JPanel panelButtons = new JPanel(); - - private final JPanel panelTree = new JPanel(); - - private final JPanel panelData = new JPanel(); - - private final JPanel panelDataTema = new JPanel(); - - private final JPanel panelDataRisco = new JPanel(); - - private final GerirMedidaPanel panelDataMedida = new GerirMedidaPanel(); - - private final LeafButton buttonTemaCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonTemaEditar = LeafIconButton.createDefaultEditButton(); - - private final LeafButton buttonTemaRemover = LeafIconButton.createDefaultRemoveButton(); - - private final LeafButton buttonRiscoCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonRiscoEditar = LeafIconButton.createDefaultEditButton(); - - private final LeafButton buttonRiscoRemover = LeafIconButton.createDefaultRemoveButton(); - - private final LeafButton buttonMedidaCriar = LeafIconButton.createDefaultNewButton(); - - private final LeafButton buttonMedidaRemover = LeafIconButton.createDefaultRemoveButton(); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - private final TreeRiscos tree = new TreeRiscos( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private final CardLayout cardLayout = new CardLayout(); - - public GerirRiscosPanel() - { - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void setupListeners() - { - buttonTemaCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarTema(); - } - } ); - buttonTemaEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarTema(); - } - } ); - buttonTemaRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerTema(); - } - } ); - buttonRiscoCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarRisco(); - } - } ); - buttonRiscoEditar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - editarRisco(); - } - } ); - buttonRiscoRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerRisco(); - } - } ); - buttonMedidaCriar.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - criarMedida(); - } - } ); - buttonMedidaRemover.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - removerMedida(); - } - } ); - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - setEnabled(); - selectCard(); - } - } ); - panelDataMedida.addPropertyChangeListener( GerirMedidaPanel.MEDIDA_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - if( evt.getNewValue() != null ) - { - doRefresh(); - } - } - } ); - } - - private void criarTema() - { - try - { - String temaString = JOptionPane.showInputDialog( this, "Criar tema", "Descri" + ccedil + atilde + "o", JOptionPane.QUESTION_MESSAGE ); - if( temaString != null ) - { - HsRiscoTemaData tema = new HsRiscoTemaData(); - tema.setDescription( temaString ); - tema.save(); - doRefresh(); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarTema() - { - try - { - HsRiscoTemaData tema = getSelectedTema(); - if( tema != null ) - { - String temaString = JOptionPane.showInputDialog( this, "Editar tema", tema.getDescription() ); - if( temaString != null ) - { - tema.setDescription( temaString ); - tema.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerTema() - { - try - { - HsRiscoTemaData tema = getSelectedTema(); - - if ( tema != null ) - { - List< HsRiscoData > riscos = tema.fromHsRisco_tema_id(); - if ( riscos != null && riscos.size() > 0 ) - { - JOptionPane.showMessageDialog( this, "O Tema seleccionado cont\u00E9m Riscos. Tem de os remover primeiro.", "Erro", JOptionPane.ERROR_MESSAGE ); - } - else if ( LeafDialog.confirmDelete( true, false, "tema" ) ) - { - tema.delete(); - doRefresh(); - } - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void criarRisco() - { - try - { - HsRiscoTemaData tema = getSelectedTema(); - if( tema == null ) - { - HsRiscoData risco = getSelectedRisco(); - if( risco != null ) - { - tema = risco.toTema_id(); - } - else - { - HsRiscoMedidaData medida = getSelectedMedida(); - if( medida != null ) - { - tema = medida.toRisco_id().toTema_id(); - } - } - } - if( tema != null ) - { - String riscoString = JOptionPane.showInputDialog( this, "Criar risco", "Descri" + ccedil + atilde + "o", JOptionPane.QUESTION_MESSAGE ); - if( riscoString != null ) - { - HsRiscoData risco = new HsRiscoData(); - risco.setDescription( riscoString ); - risco.setToTema_id( tema ); - risco.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void editarRisco() - { - try - { - HsRiscoData risco = getSelectedRisco(); - if( risco != null ) - { - String riscoString = JOptionPane.showInputDialog( this, "Editar risco", risco.getDescription() ); - if( riscoString != null ) - { - risco.setDescription( riscoString ); - risco.save(); - doRefresh(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerRisco() - { - try - { - HsRiscoData risco = getSelectedRisco(); - if ( risco != null ) - { - List< HsRiscoMedidaData > medidas = risco.fromHsRiscoMedida_risco_id(); - if ( medidas != null && medidas.size() > 0 ) - { - JOptionPane.showMessageDialog( this, "O Risco seleccionado cont\u00E9m Medidas. Tem de as remover primeiro.", "Erro", JOptionPane.ERROR_MESSAGE ); - } - else if ( LeafDialog.confirmDelete( true, false, "tema" ) ) - { - risco.delete(); - doRefresh(); - } - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private boolean removerRiscoOK( HsRiscoData risco ) - { - boolean result = true; - if( risco.fromHsRiscoEmpresa_risco_id().size() > 0 ) - { - if( JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog( this, "Este risco est" + aacute + " associado a uma ou mais empresas, \n tem a certeza que o deseja remover?", "Aviso", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ) ) - { - result = false; - } - } - return result; - } - - private void criarMedida() - { - try - { - HsRiscoData risco = getSelectedRisco(); - if( risco == null ) - { - HsRiscoMedidaData medida = getSelectedMedida(); - if( medida != null ) - { - risco = medida.toRisco_id(); - } - } - if( risco != null ) - { - HsMedidaData medida = new HsMedidaData(); - medida.setDescription( "" ); - medida.setRequesitos_legais( "" ); - medida.save(); - HsRiscoMedidaData rel = new HsRiscoMedidaData(); - rel.setToRisco_id( risco ); - rel.setToMedida_id( medida ); - rel.save(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void removerMedida() - { - try - { - HsRiscoMedidaData medida = getSelectedMedida(); - if( medida != null && LeafDialog.confirmDelete( true, false, "requisisto" ) ) - { - medida.delete(); - doRefresh(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private HsRiscoTemaData getSelectedTema() - { - return tree.getSelectedTema(); - } - - private HsRiscoData getSelectedRisco() - { - return tree.getSelectedRisco(); - } - - private HsRiscoMedidaData getSelectedMedida() - { - return tree.getSelectedMedida(); - } - - private void startupComponents() - { - panelButtons.setPreferredSize( new Dimension( 150, 0 ) ); - panelTree.setPreferredSize( new Dimension( 600, 0 ) ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - } - - private void setEnabled() - { - HsRiscoTemaData tema = getSelectedTema(); - HsRiscoData risco = getSelectedRisco(); - HsRiscoMedidaData medida = getSelectedMedida(); - buttonMedidaCriar.setEnabled( risco != null || medida != null ); - buttonRiscoCriar.setEnabled( tema != null || risco != null || medida != null ); - - buttonTemaEditar.setEnabled( tema != null ); - buttonRiscoEditar.setEnabled( risco != null ); - - buttonMedidaRemover.setEnabled( medida != null ); - buttonRiscoRemover.setEnabled( risco != null ); - buttonTemaRemover.setEnabled( tema != null ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.PREFERRED, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelButtons.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelTree.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelDataTema.setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.FILL - }, new double[] { - TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panelDataRisco.setLayout( layout ); - - panelData.setLayout( cardLayout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - panel.setBorder( BorderFactory.createTitledBorder( "Tema" ) ); - panel.setLayout( new GridLayout( 1, 3 ) ); - panel.add( buttonTemaCriar ); - panel.add( buttonTemaEditar ); - panel.add( buttonTemaRemover ); - panelButtons.add( panel, new TableLayoutConstraints( 0, 0 ) ); - panel = new JPanel(); - panel.setBorder( BorderFactory.createTitledBorder( "Risco" ) ); - panel.setLayout( new GridLayout( 1, 3 ) ); - panel.add( buttonRiscoCriar ); - panel.add( buttonRiscoEditar ); - panel.add( buttonRiscoRemover ); - panelButtons.add( panel, new TableLayoutConstraints( 1, 0 ) ); - panel = new JPanel(); - panel.setBorder( BorderFactory.createTitledBorder( "Requisito" ) ); - panel.setLayout( new GridLayout( 1, 3 ) ); - panel.add( buttonMedidaCriar ); - panel.add( buttonMedidaRemover ); - panel.add( new JPanel() ); - panelButtons.add( panel, new TableLayoutConstraints( 2, 0 ) ); - - panelTree.add( scroll, new TableLayoutConstraints( 0, 0 ) ); - - panelData.add( panelDataTema, PANEL_TEMA ); - panelData.add( panelDataRisco, PANEL_RISCO ); - panelData.add( panelDataMedida, PANEL_MEDIDA ); - - add( panelButtons, new TableLayoutConstraints( 0, 0 ) ); - add( panelTree, new TableLayoutConstraints( 0, 1 ) ); - add( panelData, new TableLayoutConstraints( 1, 1 ) ); - } - - private void selectCard() - { - HsRiscoTemaData tema = getSelectedTema(); - HsRiscoData risco = getSelectedRisco(); - HsRiscoMedidaData medida = getSelectedMedida(); - if( tema != null ) - { - cardLayout.show( panelData, PANEL_TEMA ); - } - else if( risco != null ) - { - cardLayout.show( panelData, PANEL_RISCO ); - } - else if( medida != null ) - { - cardLayout.show( panelData, PANEL_MEDIDA ); - panelDataMedida.setMedida( medida.toMedida_id() ); - } - } - - @Override - public void refresh() - { - TreePath selPath = tree.getSelectionPath(); - Object selObject = null; - if( selPath != null ) - { - Object selNode = selPath.getLastPathComponent(); - if( selNode != null && (selNode instanceof DefaultMutableTreeNode )) - { - selObject = ((DefaultMutableTreeNode)selNode).getUserObject(); - } - } - root.removeAllChildren(); - TreeTools.merge( root, HigieneSegurancaLogic.getRiscosTree() ); - TreeTools.refreshTree( tree, root, false ); - if( selObject != null ) - { - DefaultMutableTreeNode found = TreeTools.findNodeWithUserObject( selObject, root ); - if( found != null ) - { - TreePath selNew = TreeTools.getPathFor( found ); - if( selNew != null ) - { - tree.setSelectionPath( selNew ); - TreeTools.refreshTree( tree, found, false ); - } - } - } - setEnabled(); - } - - public void moverRisco( HsRiscoData from, DefaultMutableTreeNode to ) - { - - } - - public void moverRequisito( ) - { - - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/TreeRiscos.java b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/TreeRiscos.java deleted file mode 100644 index fdf4262b..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/TreeRiscos.java +++ /dev/null @@ -1,46 +0,0 @@ -package siprp.higiene.gestao.riscos; - -import java.awt.dnd.DropTarget; - -import javax.swing.tree.TreeModel; - -import shst.data.outer.HsRiscoData; -import shst.data.outer.HsRiscoMedidaData; -import shst.data.outer.HsRiscoTemaData; - -import com.evolute.swing.tree.EvoDraggableTree; - -public class TreeRiscos extends EvoDraggableTree -{ - private static final long serialVersionUID = 1L; - - public TreeRiscos( TreeModel model ) - { - super( model ); - } - - @Override - public void setDropTarget() - { - setDropTarget( new DropTarget( this , new DnDRiscosListener( this ) ) ); - } - - public HsRiscoTemaData getSelectedTema() - { - Object object = getSelectedObject(); - return object == null ? null : ((object instanceof HsRiscoTemaData) ? (HsRiscoTemaData) object : null); - } - - public HsRiscoData getSelectedRisco() - { - Object object = getSelectedObject(); - return object == null ? null : ((object instanceof HsRiscoData) ? (HsRiscoData) object : null); - } - - public HsRiscoMedidaData getSelectedMedida() - { - Object object = getSelectedObject(); - return object == null ? null : ((object instanceof HsRiscoMedidaData) ? (HsRiscoMedidaData) object : null); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/revert.png b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/revert.png deleted file mode 100644 index bd1d011a..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/revert.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/save.png b/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/save.png deleted file mode 100644 index d2d0d6e1..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/gestao/riscos/save.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidaRelatorioPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidaRelatorioPanel.java deleted file mode 100644 index 7c33ef9d..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidaRelatorioPanel.java +++ /dev/null @@ -1,306 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import shst.data.outer.HsRelatorioPostoMedidaData; -import siprp.SIPRPSpellChecker; - -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.images.ImageException; -import com.evolute.utils.images.ImageIconLoader; - -public class GerirMedidaRelatorioPanel extends JPanel -{ - - public static final String MEDIDA_CHANGED = "MEDIDA_CHANGED"; - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/riscos/save.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/riscos/revert.png"; - - private LeafButton buttonSaveMedida; - - private LeafButton buttonRevertMedida; - - private LeafButton buttonSaveRequesito; - - private LeafButton buttonRevertRequesito; - - private final JCheckBox checkPlanoActuacao = new JCheckBox( "Plano de actua" + ccedil + atilde + "o" ); - - private final JTextArea fieldTextMedida = new JTextArea(); - - private final JScrollPane scrollMedida = new JScrollPane( fieldTextMedida ); - - private final JTextArea fieldTextRequisitosLegais = new JTextArea(); - - private final JScrollPane scrollRequesitos = new JScrollPane( fieldTextRequisitosLegais ); - - private HsRelatorioPostoMedidaData relacao = null; - - public GerirMedidaRelatorioPanel() - { - try - { - buttonSaveMedida = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_SAVE ) ); - buttonRevertMedida = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_REVERT ) ); - buttonSaveRequesito = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_SAVE ) ); - buttonRevertRequesito = new LeafButton( ImageIconLoader.loadImageIcon( ICON_NAME_REVERT ) ); - } - catch( ImageException e ) - { - ErrorLogger.logException( e ); - } - catch ( IOException e ) - { - ErrorLogger.logException( e ); - } - startupComponents(); - startupLayout(); - placeComponents(); - setupListeners(); - } - - private void startupComponents() - { - fieldTextMedida.setWrapStyleWord( true ); - fieldTextMedida.setLineWrap( true ); - fieldTextRequisitosLegais.setWrapStyleWord( true ); - fieldTextRequisitosLegais.setLineWrap( true ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( fieldTextRequisitosLegais ); - SIPRPSpellChecker.getInstance().attachSpellCheckToComponent( fieldTextMedida ); - scrollMedida.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - scrollMedida.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - scrollRequesitos.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - scrollRequesitos.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); - } - - private void setupListeners() - { - checkPlanoActuacao.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - savePlano(); - } - } ); - fieldTextRequisitosLegais.addCaretListener( new CaretListener() - { - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - } ); - fieldTextMedida.addCaretListener( new CaretListener() - { - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - } ); - buttonSaveMedida.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - saveMedida(); - } - } ); - buttonSaveRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - saveRequesito(); - } - } ); - buttonRevertMedida.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revertMedida(); - } - } ); - buttonRevertRequesito.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revertRequesito(); - } - } ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( checkPlanoActuacao, new TableLayoutConstraints( 0, 0 ) ); - add( panel, new TableLayoutConstraints( 0, 0, 2, 0 ) ); - add( new JLabel( "Requisitos legais" ), new TableLayoutConstraints( 0, 1 ) ); - add( buttonSaveRequesito, new TableLayoutConstraints( 1, 1 ) ); - add( buttonRevertRequesito, new TableLayoutConstraints( 2, 1 ) ); - add( scrollRequesitos, new TableLayoutConstraints( 0, 2, 2, 2 ) ); - add( new JLabel( "Medida" ), new TableLayoutConstraints( 0, 3 ) ); - add( buttonSaveMedida, new TableLayoutConstraints( 1, 3 ) ); - add( buttonRevertMedida, new TableLayoutConstraints( 2, 3 ) ); - add( scrollMedida, new TableLayoutConstraints( 0, 4, 2, 4 ) ); - } - - private void setEnabled() - { - if( isEnabled() ) - { - boolean medidaChanged = false; - boolean requesitoChanged = false; - if( relacao != null ) - { - checkPlanoActuacao.setEnabled( true ); - medidaChanged = !fieldTextMedida.getText().equals( relacao.toMedida_id().getDescription() ); - requesitoChanged = !fieldTextRequisitosLegais.getText().equals( relacao.toMedida_id().getRequesitos_legais() ); - } - fieldTextMedida.setEnabled( relacao != null ); - fieldTextRequisitosLegais.setEnabled( relacao != null ); - buttonSaveMedida.setEnabled( medidaChanged ); - buttonSaveRequesito.setEnabled( requesitoChanged ); - buttonRevertMedida.setEnabled( medidaChanged ); - buttonRevertRequesito.setEnabled( requesitoChanged ); - } - else - { - buttonSaveMedida.setEnabled( false ); - buttonSaveRequesito.setEnabled( false ); - buttonRevertMedida.setEnabled( false ); - buttonRevertRequesito.setEnabled( false ); - fieldTextRequisitosLegais.setEnabled( false ); - fieldTextMedida.setEnabled( false ); - checkPlanoActuacao.setEnabled( false ); - } - - } - - private void savePlano() - { - try - { - if( relacao != null ) - { - relacao.setIs_plano_actuacao( checkPlanoActuacao.isSelected() ); - relacao.save(); - firePropertyChange( MEDIDA_CHANGED, null, relacao ); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void saveMedida() - { - try - { - if( relacao != null ) - { - relacao.toMedida_id().setDescription( fieldTextMedida.getText() ); - relacao.save(); - refresh(); - } - setEnabled(); - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void saveRequesito() - { - try - { - if( relacao != null ) - { - relacao.toMedida_id().setRequesitos_legais( fieldTextRequisitosLegais.getText() ); - relacao.save(); - refresh(); - } - setEnabled(); - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - private void revertMedida() - { - if( relacao != null ) - { - fieldTextMedida.setText( relacao.toMedida_id().getDescription() ); - } - setEnabled(); - } - - private void revertRequesito() - { - if( relacao != null ) - { - fieldTextRequisitosLegais.setText( relacao.toMedida_id().getRequesitos_legais() ); - } - setEnabled(); - } - - private void refresh() - { - firePropertyChange( MEDIDA_CHANGED, null, relacao ); - } - - public void setMedida( HsRelatorioPostoMedidaData medida ) - { - this.relacao = medida; - fieldTextMedida.setText( medida == null ? null : medida.toMedida_id().getDescription() ); - fieldTextRequisitosLegais.setText( medida == null ? null : medida.toMedida_id().getRequesitos_legais() ); - checkPlanoActuacao.setSelected( medida == null ? false : (medida.getIs_plano_actuacao() == null ? false : medida.getIs_plano_actuacao()) ); - setEnabled(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidasRelatorioPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidasRelatorioPanel.java deleted file mode 100644 index 02e6bc94..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirMedidasRelatorioPanel.java +++ /dev/null @@ -1,526 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.iacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Comparator; -import java.util.List; - -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTree; -import leaf.ui.TreeInserterDialog; -import shst.data.outer.HsRelatorioMedidaData; -import shst.data.outer.HsRelatorioPostoData; -import shst.data.outer.HsRelatorioPostoMedidaData; -import shst.data.outer.HsRelatorioPostoRiscoData; -import shst.data.outer.HsRelatorioRiscoData; -import shst.data.outer.HsRiscoData; -import shst.logic.HigieneSegurancaLogic; -import shst.logic.node.MedidaRelatorioNode; -import shst.logic.node.NodeRisco; -import shst.logic.node.RiscoRelatorioNode; -import siprp.higiene.gestao.SIPRPLazyLoadedPanel; - -import com.evolute.entity.evo.EvoJoinObject; -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.ui.trees.TreeTools; - -public class GerirMedidasRelatorioPanel extends SIPRPLazyLoadedPanel -{ - - private static final long serialVersionUID = 1L; - - public static final String SELECTION_CHANGED = "RISCOS_SELECTION_CHANGED"; - - public static final String VALUE_CHANGED = "VALUE_CHANGED"; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png"; - - private final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private HsRelatorioPostoData posto = null; - - private HsRelatorioPostoMedidaData selectedMedida = null; - - public GerirMedidasRelatorioPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonAdicionar.setEnabled( false ); - buttonRemover.setEnabled( false ); - TreeTools.registerTreeKeepExpandState( tree ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION ); - tree.setCellRenderer( new DefaultTreeCellRenderer() - { - - private static final long serialVersionUID = 1L; - - @Override - public Component getTreeCellRendererComponent( JTree pTree, Object pValue, boolean pIsSelected, boolean pIsExpanded, boolean pIsLeaf, int pRow, boolean pHasFocus ) - { - super.getTreeCellRendererComponent( pTree, pValue, pIsSelected, pIsExpanded, pIsLeaf, pRow, pHasFocus ); - boolean highlight = false; - Color highColor = null; - Color lowColor = null; - if( pValue instanceof RiscoRelatorioNode ) - { - Object userObject = ((RiscoRelatorioNode) pValue).getUserObject(); - if( userObject instanceof HsRelatorioPostoRiscoData ) - { - highlight = HigieneSegurancaLogic.isRelatorioRiscoPreenchido( (HsRelatorioPostoRiscoData) userObject ); - highColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK_SEL; - lowColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK; - } - } - else if( pValue instanceof MedidaRelatorioNode ) - { - Object userObject = ((MedidaRelatorioNode) pValue).getUserObject(); - if( userObject instanceof HsRelatorioPostoMedidaData ) - { - HsRelatorioPostoMedidaData medida = (HsRelatorioPostoMedidaData) userObject; - if( medida.getIs_plano_actuacao() != null ) - { - highlight = medida.getIs_plano_actuacao(); - highColor = RelatorioHigieneSegurancaWindow.COLOR_MEDIDA_OK_SEL; - lowColor = RelatorioHigieneSegurancaWindow.COLOR_MEDIDA_OK; - } - } - } - if( highlight ) - { - setOpaque( true ); - setBackground( pIsSelected ? highColor : lowColor ); - } - else - { - setOpaque( false ); - } - return (this); - } - } ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( - new double[] { TableLayout.FILL }, - new double[] { TableLayout.MINIMUM, TableLayout.FILL } - ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - JPanel panel = new JPanel(); - TableLayout layout = new TableLayout( - new double[] { TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL }, - new double[] { TableLayout.MINIMUM } - ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - panel.setLayout( layout ); - panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRemover, new TableLayoutConstraints( 1, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1 ) ); - } - - private void startupListeners() - { - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() - { - @Override - public void valueChanged( TreeSelectionEvent e ) - { - Object object = null; - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object selection = path.getLastPathComponent(); - if( selection instanceof RiscoRelatorioNode ) - { - object = selection == null ? null : ((RiscoRelatorioNode) selection).getUserObject(); - setEnabled(); - } - else if( selection instanceof MedidaRelatorioNode ) - { - object = selection == null ? null : ((MedidaRelatorioNode) selection).getUserObject(); - selectedMedida = (HsRelatorioPostoMedidaData) object; - setEnabled(); - } - } - firePropertyChange( SELECTION_CHANGED, null, object ); - } - } ); - buttonAdicionar.addActionListener( new ActionListener() - { - - @Override - public void actionPerformed( ActionEvent e ) - { - add(); - - } - - } ); - buttonRemover.addActionListener( new ActionListener() - { - - @Override - public void actionPerformed( ActionEvent e ) - { - rem(); - } - - } ); - } - - private HsRelatorioPostoRiscoData getSelectedRisco() - { - HsRelatorioPostoRiscoData result = null; - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object selection = path.getLastPathComponent(); - if( selection instanceof RiscoRelatorioNode ) - { - result = selection == null ? null : (HsRelatorioPostoRiscoData) ((RiscoRelatorioNode) selection).getUserObject(); - } - } - return result; - } - - private HsRelatorioPostoMedidaData getSelectedMedida() - { - HsRelatorioPostoMedidaData result = null; - TreePath path = tree.getSelectionPath(); - if( path != null ) - { - Object selection = path.getLastPathComponent(); - if( selection instanceof MedidaRelatorioNode ) - { - result = selection == null ? null : (HsRelatorioPostoMedidaData) ((MedidaRelatorioNode) selection).getUserObject(); - } - } - return result; - } - - private void add() - { - try - { - setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ); - DefaultMutableTreeNode allRiscos = getAllRiscos(); - TreeTools.removeAll( allRiscos, getRiscosTree() ); - TreeInserterDialog dialog = new TreeInserterDialog( "Adicionar Riscos", allRiscos ); - final DefaultMutableTreeNode result = dialog.getResult(); - if( result != null ) - { - runAsynchronously( new Runnable() - { - @Override - public void run() - { - addResult( result ); - doRefresh(); - } - } ); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - finally - { - setCursor( Cursor.getDefaultCursor() ); - } - } - - private DefaultMutableTreeNode getAllRiscos() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - if( posto != null ) - { - result = HigieneSegurancaLogic.getRiscosTree( posto.toArea_id().toRelatorio_id().toMarcacao_id().toEstabelecimento_id().toEmpresa_id() ); - } - return result; - } - - private DefaultMutableTreeNode getRiscosTree() - { - DefaultMutableTreeNode result = new DefaultMutableTreeNode(); - for( int i = 0; i < root.getChildCount(); ++i ) - { - DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) root.getChildAt( i ); - HsRelatorioPostoRiscoData relPostoRisco = null; - if( childNode instanceof RiscoRelatorioNode ) - { - relPostoRisco = (HsRelatorioPostoRiscoData) ((RiscoRelatorioNode) childNode).getUserObject(); - } - HsRelatorioRiscoData relRisco = relPostoRisco == null ? null : relPostoRisco.toRisco_id(); - if( relRisco != null ) - { - HsRiscoData risco = HigieneSegurancaLogic.findHsRiscoFor( relRisco ); - if( risco != null ) - { - result.add( new NodeRisco( risco ) ); - } - } - } - return result; - } - - private void addResult( DefaultMutableTreeNode root ) - { - if( root != null ) - { - if( root instanceof NodeRisco ) - { - HsRiscoData risco = (HsRiscoData) ((NodeRisco)root).getUserObject(); - addRisco( posto == null ? null : posto.toArea_id().getRelatorio_id(), risco ); - } - for( int i = 0; i < root.getChildCount(); ++i ) - { - addResult( (DefaultMutableTreeNode) root.getChildAt( i ) ); - } - } - } - - private void addRisco( Integer relatorioID, HsRiscoData risco ) - { - if( posto != null ) - { - try - { - HsRelatorioRiscoData oldRisco = HigieneSegurancaLogic.getRelatorioRiscoData( posto, risco.getId() ); - if( oldRisco == null || ask( "Actualizar risco?", "O risco: " + risco.toString() + "\nJ" + aacute + " est" + aacute + " inclu" + iacute + "do no relat" + oacute + "rio.\nDeseja actualiz" + aacute + "-lo?") ) - { - HigieneSegurancaLogic.addRiscoToRelatorioPosto( risco, oldRisco, posto ); - } - } - catch ( Exception e ) - { - ErrorLogger.logExceptionAndShow( e ); - } - } - } - - private boolean confirm( String message ) - { - return JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( this, message, "Confirma"+ccedil+atilde+"o", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - } - - private void rem() - { - final TreePath [] paths = tree.getSelectionPaths(); - if( paths != null && paths.length > 0 ) - { - if( confirm( "Tem a certeza que deseja remover a selec" + ccedil + atilde + "o?\n - " + paths.length + " risco(s)/medida(s)" ) ) - { - runAsynchronously( new Runnable() - { - @Override - public void run() - { - for( TreePath path : paths ) - { - if ( !rem( path ) ) - { - break; - } - } - doRefresh(); - } - } ); - } - } - } - - private boolean rem( TreePath path ) - { - boolean outcome = false; - try - { - if( path != null ) - { - Object selection = path.getLastPathComponent(); - if( selection instanceof MedidaRelatorioNode ) - { - HsRelatorioPostoMedidaData rel = selection == null ? null : (HsRelatorioPostoMedidaData) ((MedidaRelatorioNode) selection).getUserObject(); - if( rel != null ) - { - HsRelatorioMedidaData medidaData = rel.toMedida_id(); - medidaData.delete(); - rel.delete(); - outcome = true; - } - } - else if( selection instanceof RiscoRelatorioNode ) - { - HsRelatorioPostoRiscoData rel = (HsRelatorioPostoRiscoData) ((RiscoRelatorioNode)selection).getUserObject(); - if( rel != null ) - { - HsRelatorioRiscoData riscoData = rel.toRisco_id(); - MedidasRiscosDeleterController.getInstance().delete( new MedidasRiscosDeleter( riscoData ) ); - riscoData.delete(); - rel.delete(); - outcome = true; - } - } - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - return outcome; - } - - private void setEnabled() - { - boolean add = false; - boolean rem = false; - if( posto != null ) - { - if( posto.toArea_id() != null && posto.toArea_id().toRelatorio_id() != null && posto.toArea_id().toRelatorio_id().getIs_submetido() == null ) - { - add = true; - rem = true; - } - } - buttonAdicionar.setEnabled( add ); - buttonRemover.setEnabled( rem && ( getSelectedMedida() != null || getSelectedRisco() != null ) ); - } - - @Override - public void refresh() - { - root.removeAllChildren(); - - if( posto != null ) - { - try - { - List objects = HigieneSegurancaLogic.getRelatorioMedidasForPosto( posto ); - RiscoRelatorioNode riscoNode = null; - for( EvoJoinObject evoJoinObject : objects ) - { - HsRelatorioPostoRiscoData postoRisco = evoJoinObject.getObject( HsRelatorioPostoRiscoData.class ); - HsRelatorioPostoMedidaData postoMedida = evoJoinObject.getObject( HsRelatorioPostoMedidaData.class ); - if( riscoNode == null || ! postoRisco.equals( ( HsRelatorioPostoRiscoData ) riscoNode.getUserObject() ) ) - { - riscoNode = new RiscoRelatorioNode( postoRisco ); - root.add( riscoNode ); - } - if( postoMedida != null && postoMedida.toMedida_id().getDeleted_date() == null ) - { - riscoNode.add( new MedidaRelatorioNode( postoMedida ) ); - } - } - } - catch ( Exception e ) - { - ErrorLogger.logExceptionAndShow( e ); - } - } - - TreeTools.sort( root, new Comparator() - { - @Override - public int compare( DefaultMutableTreeNode o1, DefaultMutableTreeNode o2 ) - { - Integer result = null; - if( (o1 instanceof RiscoRelatorioNode) && o2 instanceof RiscoRelatorioNode ) - { - HsRelatorioPostoRiscoData risco1 = (HsRelatorioPostoRiscoData) o1.getUserObject(); - HsRelatorioPostoRiscoData risco2 = (HsRelatorioPostoRiscoData) o2.getUserObject(); - if( risco1 != null ) - { - return risco1.compareTo( risco2 == null ? null : risco2 ); - } - } - return result == null ? o1.toString().compareTo( o2.toString() ) : result; - } - }); - - TreeTools.refreshTree( tree, root, false ); - if( selectedMedida != null ) - { - selectMedida(); - } - - setEnabled(); - } - - private void selectMedida( ) - { - DefaultMutableTreeNode node = TreeTools.findNodeWithUserObject( selectedMedida, root ); - if( node != null ) - { - TreePath path = TreeTools.getPathFor( node ); - if( path != null ) - { - tree.setSelectionPath( path ); - } - } - else - { - selectedMedida = null; - } - } - - public void setPosto( HsRelatorioPostoData posto ) - { - this.posto = posto; - this.selectedMedida = null; - doRefresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirValoresRiscoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirValoresRiscoPanel.java deleted file mode 100644 index b8bfccab..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/GerirValoresRiscoPanel.java +++ /dev/null @@ -1,336 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.ButtonGroup; -import javax.swing.JComboBox; -import javax.swing.JFormattedTextField; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import shst.data.outer.HsRelatorioPostoRiscoData; -import shst.data.outer.HsRelatorioRiscoValorQualitativoData; -import shst.logic.HigieneSegurancaLogic; - -import com.evolute.utils.documents.IntegerDocument; - -public class GerirValoresRiscoPanel extends JPanel implements ActionListener, CaretListener -{ - - private static final long serialVersionUID = 1L; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/riscos/save.png"; - - private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/riscos/revert.png"; - - public static final String VALUE_CHANGED = "VALUE_CHANGED"; - - private final JRadioButton radioValorQuantitativo = new JRadioButton(); - - private final JRadioButton radioValorQualitativo = new JRadioButton(); - - private final JFormattedTextField textSeveridade = new JFormattedTextField(); - - private final JFormattedTextField textProbabilidade = new JFormattedTextField(); - - private final JComboBox comboValorQualitativo = new JComboBox(); - - private final LeafButton buttonSave = LeafIconButton.createButton( ICON_NAME_SAVE ); - - private final LeafButton buttonRevert = LeafIconButton.createButton( ICON_NAME_REVERT ); - - private final ButtonGroup bg = new ButtonGroup(); - - private HsRelatorioPostoRiscoData valoresRisco = null; - - public GerirValoresRiscoPanel() - { - startupListeners(); - startupComponents(); - startupLayout(); - placeComponents(); - loadValoresQualitativos(); - } - - private void startupListeners() - { - radioValorQualitativo.addActionListener( this ); - radioValorQuantitativo.addActionListener( this ); - comboValorQualitativo.addActionListener( this ); - textProbabilidade.addCaretListener( this ); - textSeveridade.addCaretListener( this ); - buttonSave.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - save(); - } - } ); - buttonRevert.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - refresh(); - } - } ); - - } - - private void startupComponents() - { - textSeveridade.setPreferredSize( new Dimension( 30, 0 ) ); - textSeveridade.setDocument( new IntegerDocument( 1, false ) ); - textProbabilidade.setPreferredSize( new Dimension( 30, 0 ) ); - textProbabilidade.setDocument( new IntegerDocument( 1, false ) ); - buttonSave.setEnabled( false ); - buttonRevert.setEnabled( false ); - bg.add( radioValorQualitativo ); - bg.add( radioValorQuantitativo ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM - } ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - JPanel panel = new JPanel(); - panel.setLayout( layout ); - panel.add( buttonSave, new TableLayoutConstraints( 1, 0 ) ); - panel.add( buttonRevert, new TableLayoutConstraints( 2, 0 ) ); - - add( panel, new TableLayoutConstraints( 1, 0, 6, 0 ) ); - add( radioValorQuantitativo, new TableLayoutConstraints( 0, 1 ) ); - add( new JLabel( "Severidade" ), new TableLayoutConstraints( 1, 1 ) ); - add( textSeveridade, new TableLayoutConstraints( 2, 1 ) ); - add( new JLabel( "Probabilidade" ), new TableLayoutConstraints( 4, 1 ) ); - add( textProbabilidade, new TableLayoutConstraints( 5, 1 ) ); - add( radioValorQualitativo, new TableLayoutConstraints( 0, 2 ) ); - add( comboValorQualitativo, new TableLayoutConstraints( 1, 2, 5, 2 ) ); - } - - private void loadValoresQualitativos() - { - comboValorQualitativo.removeAllItems(); - for( HsRelatorioRiscoValorQualitativoData valor : HigieneSegurancaLogic.getAllValoresQualitativos() ) - { - comboValorQualitativo.addItem( valor ); - } - } - - void refresh() - { - if( valoresRisco != null ) - { - boolean qualitativo = valoresRisco.toValor_qualitativo_id() != null; - radioValorQuantitativo.setSelected( !qualitativo ); - radioValorQualitativo.setSelected( qualitativo ); - String severidade = (valoresRisco.getSeveridade() == null ? null : valoresRisco.getSeveridade() + ""); - String probabilidade = (valoresRisco.getProbabilidade() == null ? null : valoresRisco.getProbabilidade() + ""); - textSeveridade.setText( severidade ); - textProbabilidade.setText( probabilidade ); - if( valoresRisco.toValor_qualitativo_id() != null ) - { - comboValorQualitativo.setSelectedItem( valoresRisco.toValor_qualitativo_id() ); - } -// else -// { -// comboValorQualitativo.setSelectedIndex( -1 ); -// } - } - else - { - bg.clearSelection(); - textSeveridade.setText( null ); - textProbabilidade.setText( null ); -// comboValorQualitativo.setSelectedIndex( -1 ); - } - } - - private void setEnabled() - { - if( isEnabled() ) - { - textProbabilidade.setEnabled( valoresRisco != null && radioValorQuantitativo.isSelected() ); - textSeveridade.setEnabled( valoresRisco != null && radioValorQuantitativo.isSelected() ); - radioValorQualitativo.setEnabled( valoresRisco != null ); - radioValorQuantitativo.setEnabled( valoresRisco != null ); - comboValorQualitativo.setEnabled( valoresRisco != null && radioValorQualitativo.isSelected() ); - if( valoresRisco != null ) - { - boolean changes = false; - boolean wasQual = valoresRisco.toValor_qualitativo_id() != null; - boolean isQual = radioValorQualitativo.isSelected(); - if( !isQual ) - { - changes = wasQual; - if( !changes ) - { - boolean probChanged = false; - boolean sevChanged = false; - String prob = textProbabilidade.getText(); - String sev = textSeveridade.getText(); - if( prob == null ) - { - probChanged = valoresRisco.getProbabilidade() != null; - } - else - { - probChanged = !prob.equals( valoresRisco.getProbabilidade() == null ? "" : valoresRisco.getProbabilidade() + "" ); - } - if( sev == null ) - { - sevChanged = valoresRisco.getSeveridade() != null; - } - else - { - sevChanged = !sev.equals( valoresRisco.getSeveridade() == null ? "" : valoresRisco.getSeveridade() + "" ); - } - changes = probChanged || sevChanged; - } - } - else - { - changes = !wasQual; - if( !changes ) - { - changes = !comboValorQualitativo.getSelectedItem().equals( valoresRisco.toValor_qualitativo_id() ); - } - } - buttonSave.setEnabled( changes ); - buttonRevert.setEnabled( changes ); - } - } - else - { - buttonRevert.setEnabled( false ); - buttonSave.setEnabled( false ); - radioValorQualitativo.setEnabled( false ); - radioValorQuantitativo.setEnabled( false ); - comboValorQualitativo.setEnabled( false ); - textProbabilidade.setEnabled( false ); - textSeveridade.setEnabled( false ); - } - } - - public void setRelatorioPostoRisco( HsRelatorioPostoRiscoData rel ) - { - this.valoresRisco = rel; - refresh(); - setEnabled(); - } - - private void error( boolean probabilidade ) - { - JOptionPane.showMessageDialog( this, "Valor inv" + aacute + "lido para " + (probabilidade ? "'Probabilidade'" : "'Severidade'") + ".", "Erro", JOptionPane.ERROR_MESSAGE, null ); - } - - private void save() - { - try - { - if( valoresRisco != null ) - { - if( radioValorQualitativo.isSelected() ) - { - valoresRisco.setToValor_qualitativo_id( (HsRelatorioRiscoValorQualitativoData) comboValorQualitativo.getSelectedItem() ); - valoresRisco.setProbabilidade( null ); - valoresRisco.setSeveridade( null ); - } - else - { - valoresRisco.setToValor_qualitativo_id( null ); - Integer probabilidade = null; - Integer severidade = null; - boolean ok = true; - if( textProbabilidade.getText() != null && !textProbabilidade.getText().trim().equals( "" ) ) - { - try - { - probabilidade = new Integer( textProbabilidade.getText() ); - } catch( NumberFormatException e1 ) - { - ok = false; - } - if( !ok || !HigieneSegurancaLogic.isProbabilidadeValida( probabilidade ) ) - { - error( true ); - } - } - if( textSeveridade.getText() != null && !textSeveridade.getText().trim().equals( "" ) ) - { - if( ok ) - { - try - { - severidade = new Integer( textSeveridade.getText() ); - } catch( NumberFormatException e2 ) - { - ok = false; - } - if( !ok || !HigieneSegurancaLogic.isSeveridadeValida( severidade ) ) - { - error( false ); - } - } - } - boolean pvalid = HigieneSegurancaLogic.isProbabilidadeValida( probabilidade ); - boolean svalid = HigieneSegurancaLogic.isSeveridadeValida( severidade ); - - valoresRisco.setProbabilidade( pvalid && svalid ? probabilidade : null ); - valoresRisco.setSeveridade( pvalid && svalid ? severidade : null ); - } - valoresRisco.save(); - firePropertyChange( VALUE_CHANGED, null, valoresRisco ); - refresh(); - setEnabled(); - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - - @Override - public void caretUpdate( CaretEvent e ) - { - setEnabled(); - } - - @Override - public void actionPerformed( ActionEvent e ) - { - setEnabled(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleter.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleter.java deleted file mode 100644 index b4fd1e8a..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package siprp.higiene.relatorio; - -import shst.data.outer.HsRelatorioMedidaData; -import shst.data.outer.HsRelatorioPostoMedidaData; -import shst.data.outer.HsRelatorioRiscoData; - -import com.evolute.utils.error.ErrorLogger; - - -public class MedidasRiscosDeleter implements Runnable -{ - private HsRelatorioRiscoData riscoData; - - private String name; - - public MedidasRiscosDeleter( HsRelatorioRiscoData riscoData ) - { - this.riscoData = riscoData; - - setName( "Delete Medidas from Risco - " + riscoData ); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public void run() - { - try - { - for( HsRelatorioMedidaData medida : riscoData.fromHsRelatorioMedida_risco_id() ) - { - for ( HsRelatorioPostoMedidaData relMedida : medida.fromHsRelatorioPostoMedida_medida_id() ) - { - relMedida.delete(); - } - medida.delete(); - } - } - catch ( Exception e ) - { - ErrorLogger.logException( e ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleterController.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleterController.java deleted file mode 100644 index cdb0be80..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/MedidasRiscosDeleterController.java +++ /dev/null @@ -1,34 +0,0 @@ -package siprp.higiene.relatorio; - -import java.util.Vector; - -public class MedidasRiscosDeleterController -{ - private static MedidasRiscosDeleterController INSTANCE = null; - - private final Vector threads = new Vector(); - - public static synchronized MedidasRiscosDeleterController getInstance() - { - if ( INSTANCE == null ) - { - INSTANCE = new MedidasRiscosDeleterController(); - } - return INSTANCE; - } - - public Vector getThreads() - { - return threads; - } - - public void delete( MedidasRiscosDeleter thread ) - { - Thread t = new Thread( thread ); - t.setName( thread.getName() ); - t.setDaemon( false ); - t.start(); - getThreads().add( t ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PanelRelatorio.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PanelRelatorio.java deleted file mode 100644 index 3d16d78f..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PanelRelatorio.java +++ /dev/null @@ -1,780 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.aacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.eacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.iacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; -import static com.evolute.utils.strings.UnicodeLatin1Map.otilde; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.EventObject; -import java.util.List; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.event.CaretEvent; -import javax.swing.event.CaretListener; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import leaf.ui.LeafButton; -import leaf.ui.LeafDialog; -import leaf.ui.LeafIconButton; -import leaf.ui.LeafTextAreaEditor; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsEmailEstabelecimentoData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.MarcacoesEstabelecimentoData; -import shst.data.outer.MarcacoesTecnicosHstData; -import shst.logic.HigieneSegurancaLogic; -import siprp.higiene.gestao.equipamentos.AdicionarEquipamentosPanel; -import siprp.higiene.relatorio.print.RelatorioPDFCreator; -import siprp.medicina.processo.mail.MailDialog; -import siprp.medicina.processo.mail.MailSender; -import siprp.planoactuacao.print.PlanoActuacaoPDFCreator; -import siprp.ui.SIPRPFrame; - -import com.evolute.adt.Validator; -import com.evolute.swing.frame.EvoFrame; -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.ui.calendar.JCalendarPanel; - -public class PanelRelatorio extends JPanel implements CaretListener, ChangeListener, ActionListener -{ - - private static final long serialVersionUID = 1L; - - private static final int MAX_NOME_ESTABELECIMENTO_ON_FILENAME = 10; - - private static final String DEFAULT_FUNCIONARIOS_TEXT = "A empresa supracitada possui ? funcionários, sendo que ? destes exercem actividades na zona de produtos frescos."; - - private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/riscos/save.png"; - public static final String ICON_NAME_REVERT = "siprp/higiene/gestao/riscos/revert.png"; - public static final String ICON_NAME_SUBMIT = "siprp/higiene/relatorio/submit.png"; - public static final String ICON_NAME_PDF = "siprp/higiene/relatorio/adobe_reader.png"; - public static final String ICON_NAME_UNDO = "siprp/higiene/relatorio/revert.png"; - - private final JCalendarPanel dataRelatorio = new JCalendarPanel( null ); - - private final JRadioButton radioInicial = new JRadioButton( "Inicial" ); - private final JRadioButton radioPeriodica = new JRadioButton( "Peri" + oacute + "dica" ); - - private final JTextField fieldTecnico = new JTextField(); - - private final JTextField fieldTecnicoSuperior = new JTextField(); - - private final JPanel panelAcompanhantes = new JPanel(); - - private final JTextField fieldNome1 = new JTextField(); - private final JTextField fieldNome2 = new JTextField(); - - private final JTextField fieldFuncao1 = new JTextField(); - private final JTextField fieldFuncao2 = new JTextField(); - - private final LeafIconButton buttonSave = LeafIconButton.createButton( ICON_NAME_SAVE ); - private final LeafIconButton buttonRevertText = LeafIconButton.createButton( ICON_NAME_REVERT ); - private final LeafIconButton buttonSubmit = LeafIconButton.createButton( "Submeter", ICON_NAME_SUBMIT ); - private final LeafIconButton buttonPdfPlano = LeafIconButton.createButton( "Plano de actua" + ccedil + atilde + "o", ICON_NAME_PDF ); - private final LeafIconButton buttonPdfRelatorio = LeafIconButton.createButton( "Relat" + oacute + "rio", ICON_NAME_PDF ); - private final LeafButton buttonRevertPlano = LeafIconButton.createButton( "Recarregar", ICON_NAME_UNDO ); - - private final JTabbedPane tabsRelatorio = new JTabbedPane(); - - private final AdicionarEquipamentosPanel panelEquipamentos = new AdicionarEquipamentosPanel(); - - private final LeafTextAreaEditor panelFuncionarios = new LeafTextAreaEditor( new Validator() - { - @Override - public boolean isValid( String text ) - { - return !DEFAULT_FUNCIONARIOS_TEXT.equals( text ); - } - }); - - private final JTabbedPane tabsPlanoActuacao = new JTabbedPane(); - - private final PlanoActuacaoPanel panelPlano = new PlanoActuacaoPanel(); - - private final RelatorioLegislacaoPanel panelLegislacao = new RelatorioLegislacaoPanel(); - - private final RelatorioNormalizacaoPanel panelNormalizacao = new RelatorioNormalizacaoPanel(); - - ButtonGroup bg = new ButtonGroup(); - - private HsRelatorioData relatorio = null; - - public PanelRelatorio() - { - setupListeners(); - startupComponents(); - startupLayout(); - placeComponents(); - } - - private void startupComponents() - { - dataRelatorio.setPreferredSize( new Dimension( 150, 0 ) ); - panelEquipamentos.setPreferredSize( new Dimension( 400, 0 ) ); - bg.add( radioInicial ); - bg.add( radioPeriodica ); - panelAcompanhantes.setBorder( BorderFactory.createTitledBorder( "Pessoas que acompanharam" ) ); - tabsRelatorio.addTab( "Funcion" + aacute + "rios", panelFuncionarios ); - tabsRelatorio.addTab( "Equipamentos de medi"+ccedil+atilde+"o", panelEquipamentos ); - tabsPlanoActuacao.addTab( "Plano de actua" + ccedil + atilde + "o", panelPlano ); - tabsPlanoActuacao.addTab( "Legisla" + ccedil + atilde + "o", panelLegislacao ); - tabsPlanoActuacao.addTab( "Normaliza" + ccedil + atilde + "o", panelNormalizacao ); - buttonSave.setToolTipText( "Guardar" ); - buttonRevertText.setToolTipText( "Reverter" ); - buttonRevertPlano.setToolTipText( "Carregar dados do estabelecimento" ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.PREFERRED - }, new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL - } ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - setLayout( layout ); - - layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.FILL - }, new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM - } ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - panelAcompanhantes.setLayout( layout ); - } - - private void placeComponents() - { - panelAcompanhantes.add( new JLabel( "Nome" ), new TableLayoutConstraints( 0, 0 ) ); - panelAcompanhantes.add( fieldNome1, new TableLayoutConstraints( 1, 0 ) ); - panelAcompanhantes.add( new JLabel( "Fun" + ccedil + atilde + "o" ), new TableLayoutConstraints( 2, 0 ) ); - panelAcompanhantes.add( fieldFuncao1, new TableLayoutConstraints( 3, 0 ) ); - panelAcompanhantes.add( new JLabel( "Nome" ), new TableLayoutConstraints( 0, 1 ) ); - panelAcompanhantes.add( fieldNome2, new TableLayoutConstraints( 1, 1 ) ); - panelAcompanhantes.add( new JLabel( "Fun" + ccedil + atilde + "o" ), new TableLayoutConstraints( 2, 1 ) ); - panelAcompanhantes.add( fieldFuncao2, new TableLayoutConstraints( 3, 1 ) ); - - TableLayout layout = new TableLayout( new double[] { - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, - TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, - TableLayout.MINIMUM, TableLayout.MINIMUM - }, new double[] { - TableLayout.MINIMUM - } ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - JPanel panel = new JPanel(); - panel.setLayout( layout ); - - panel.add( buttonSave, new TableLayoutConstraints( 0, 0 ) ); - panel.add( buttonRevertText, new TableLayoutConstraints( 1, 0 ) ); - panel.add( buttonPdfRelatorio, new TableLayoutConstraints( 3, 0 ) ); - panel.add( buttonPdfPlano, new TableLayoutConstraints( 4, 0 ) ); - panel.add( buttonRevertPlano, new TableLayoutConstraints( 5, 0 ) ); - panel.add( buttonSubmit, new TableLayoutConstraints( 6, 0 ) ); - - add( panel, new TableLayoutConstraints( 0, 0, 7, 0 ) ); - add( new JLabel( "Data do relat" + oacute + "rio" ), new TableLayoutConstraints( 0, 1, 2, 1 ) ); - add( dataRelatorio, new TableLayoutConstraints( 3, 1 ) ); - JLabel labelAvaliacao = new JLabel( "Avalia" + ccedil + atilde + "o" ); - labelAvaliacao.setHorizontalAlignment( JLabel.RIGHT ); - add( labelAvaliacao , new TableLayoutConstraints( 4, 1 ) ); - add( radioInicial, new TableLayoutConstraints( 5, 1 ) ); - add( radioPeriodica, new TableLayoutConstraints( 6, 1 ) ); - add( new JLabel( "T" + eacute + "cnico de H.S." ), new TableLayoutConstraints( 0, 2, 2, 2 ) ); - add( fieldTecnico, new TableLayoutConstraints( 3, 2, 6, 2 ) ); - add( new JLabel( "T" + eacute + "cnico Superior de H.S." ), new TableLayoutConstraints( 0, 3, 2, 3 ) ); - add( fieldTecnicoSuperior, new TableLayoutConstraints( 3, 3, 6, 3 ) ); - add( tabsRelatorio, new TableLayoutConstraints( 7, 1, 7, 4 ) ); - add( panelAcompanhantes, new TableLayoutConstraints( 0, 4, 6, 4 ) ); - add( tabsPlanoActuacao, new TableLayoutConstraints( 0, 5, 7, 5 ) ); - } - - private void setupListeners() - { - fieldFuncao1.addCaretListener( this ); - fieldFuncao2.addCaretListener( this ); - fieldNome1.addCaretListener( this ); - fieldNome2.addCaretListener( this ); - dataRelatorio.addChangeListener( this ); - radioInicial.addActionListener( this ); - radioPeriodica.addActionListener( this ); - buttonSave.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - save(); - } - } ); - buttonRevertText.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revert(); - } - } ); - buttonSubmit.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - if( isValidEmail() || JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(null, "Emails n" + atilde + "o preenchidos para este estabelecimento!\nContinuar?", "Aviso", JOptionPane.YES_NO_OPTION ) ) - { - if( isValidPlano() && confirmSubmit() ) - { - submit(); - } - } - } - } ); - buttonPdfPlano.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - pdf(true); - } - } ); - buttonPdfRelatorio.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - pdf(false); - } - } ); - buttonRevertPlano.addActionListener( new ActionListener() - { - @Override - public void actionPerformed( ActionEvent e ) - { - revert(true); - } - } ); - panelFuncionarios.addPropertyChangeListener( LeafTextAreaEditor.ACTION_SAVE, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - try - { - String text = (String) evt.getNewValue(); - if( text != null && relatorio != null ) - { - text = text.trim(); - if( text.length() == 0 ) - { - text = null; - } - else if( text.equals( DEFAULT_FUNCIONARIOS_TEXT ) ) - { - text = null; - } - } - relatorio.setFuncionarios( text ); - relatorio.save(); - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - } - } ); - } - - protected void revert( boolean ask ) - { - if( relatorio != null ) - { -// try -// { -// setCursor( new Cursor( Cursor.WAIT_CURSOR ) ); - int ret = ask == false ? JOptionPane.YES_OPTION : JOptionPane.showConfirmDialog( this, "Todas as altera" + ccedil + otilde + "es ao plano de actua" + ccedil + atilde + "o ser" + atilde + "o perdidas\nTem a certeza?","Carregar dados do estabelecimento",JOptionPane.YES_NO_OPTION); - if( JOptionPane.YES_OPTION == ret ) - { - EvoFrame.findParentEvoFrame( this ).runAsynchronously( new Runnable() { - - @Override - public void run() - { - HigieneSegurancaLogic.reverterRelatorio(relatorio); - SwingUtilities.invokeLater( new Runnable() { - - @Override - public void run() - { - if( relatorio != null ) - { - try - { - relatorio.save(); - } - catch( Exception e ) - { - ErrorLogger.logException(e); - } - } - setRelatorio( relatorio, false ); - } - }); - } - }); - } -// } -// finally -// { -// setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) ); -// } - } - } - - private boolean isValidEmail() - { - boolean result = false; - List emails = relatorio.toMarcacao_id().toEstabelecimento_id().fromHsEmailEstabelecimento_estabelecimento_id(); - result = emails != null && emails.size() > 0; - return result; - } - - private boolean isValidPlano() - { - boolean result = false; - result = panelPlano.isValidPlano(); - if( !result ) - { - JOptionPane.showMessageDialog( null, "Todos os riscos devem ser preenchidos antes da submiss"+ atilde + "o do plano de actua" + ccedil + atilde+ "o!", "Erro", JOptionPane.ERROR_MESSAGE, null ); - } - return result; - } - - private boolean confirmSubmit() - { - return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( null, "Ao submeter o Plano de Actua"+ccedil+atilde+"o n"+atilde+"o ser"+aacute+" mais poss"+iacute+"vel alter"+aacute+"-lo. Deseja continuar?" ); - } - - private void submit() - { - try - { - setCursor(new Cursor(Cursor.WAIT_CURSOR)); - if( relatorio != null ) - { - if( sendMail( relatorio ) ) - { - refresh(); - relatorio.setIs_submetido( new java.sql.Timestamp( new Date().getTime() ) ); - relatorio.save(); - setRelatorio( relatorio, false ); - } - else - { - JOptionPane.showMessageDialog( this, "Erro ao enviar o email, o plano n"+atilde+"o ser"+aacute+" submetido." ); - } - } - } - catch( Exception e ) - { - LeafDialog.error(e); - refresh(); - } - finally - { - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); - } - } - - private boolean confirmDelete( File file ) - { - boolean result = false; - result = JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( this, "Ficheiro j" + aacute + " existente, deseja substituir?", "Aviso", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null ); - return result; - } - - private void pdf(boolean plano) - { - try - { - setCursor( new Cursor(Cursor.WAIT_CURSOR) ); - byte [] pdf = null; - if( plano ) - { - PlanoActuacaoPDFCreator creator = new PlanoActuacaoPDFCreator(); - pdf = creator.createPDF( relatorio.getId(), false ); - } - else - { - RelatorioPDFCreator creator = new RelatorioPDFCreator(); - pdf = creator.createPDF( relatorio.getId() ); - } - if( !printToFile( pdf ) ) - { - throw new Exception( "ERRO: NULL " + ( plano ? "p " : "r " ) + relatorio.getId() ); - } - } - catch( Exception e ) - { - LeafDialog.error( e ); - } - finally - { - setCursor( new Cursor(Cursor.DEFAULT_CURSOR) ); - } - } - - private boolean printToFile( byte [] pdf ) throws IOException - { - - if( pdf != null ) - { - JFileChooser fileChooser = new JFileChooser( ); - if( fileChooser.showSaveDialog( this ) == JFileChooser.APPROVE_OPTION ) - { - File file = fileChooser.getSelectedFile(); - String path = file.getAbsolutePath(); - if( !path.toUpperCase().endsWith( ".PDF" ) ) - { - path += ".pdf"; - file = new File( path ); - } - if( file != null ) - { - if( file.exists() && confirmDelete( file ) ) - { - file.delete(); - } - FileOutputStream a = new FileOutputStream(file); - a.write( pdf ); - a.close(); - } - } - } - return pdf != null; - } - - private SIPRPFrame getFrame( ) - { - Component comp = this; - SIPRPFrame frame = null; - while( comp != null ) - { - if( comp.getParent() instanceof RelatorioHigieneSegurancaWindow ) - { - frame = (RelatorioHigieneSegurancaWindow) comp.getParent(); - break; - } - comp = comp.getParent(); - } - return frame; - } - - private boolean sendMail( HsRelatorioData relatorio ) throws Exception - { - boolean result = false; - List rels = relatorio.toMarcacao_id().toEstabelecimento_id().fromHsEmailEstabelecimento_estabelecimento_id(); - String to = ""; - String bcc = ""; - for( HsEmailEstabelecimentoData rel : rels ) - { - if( to.isEmpty() ) - { - to += rel.toEmail_id().getEmail(); - } - else - { - bcc += rel.toEmail_id().getEmail() + ", "; - } - } - if(bcc.endsWith( ", " )) - { - bcc = bcc.substring( 0, bcc.length() - 2 ); - } - if( to.length() > 0 ) - { - String nomeEstabelecimento = relatorio.toMarcacao_id().toEstabelecimento_id().getNome(); - MarcacoesTecnicosHstData tecnico = relatorio.toMarcacao_id().toTecnico_hst(); - String nomeTecnico = tecnico == null ? "" : tecnico.getNome(); - Date dataVisita = relatorio.toMarcacao_id().getData(); - String dataVisitaString = new SimpleDateFormat("dd/MM/yyyy").format( dataVisita ); - String subject = "Relat" + oacute + "rio da Avalia" + ccedil + atilde + "o de Riscos Laborais e Plano de Actua" + ccedil + atilde + "o de " + nomeEstabelecimento + " - auditoria de " + dataVisitaString; - String body = "

Exmos. Senhores" + - "
" + - "
" + - "
" + - "Junto enviamos o relat" + oacute + "rio de avalia" + ccedil + atilde + "o de riscos laborais e " + - "respectivo plano de actua" + ccedil + atilde + "o da auditoria realizada no dia " + - dataVisitaString + - " ao vosso estabelecimento de(o) " + - nomeEstabelecimento + - ". Aconselhamos que tenham em conta as n" + atilde + "o conformidades indicadas " + - "nestes documentos e que preencham o plano de actua" + ccedil + atilde + "o por forma a " + - "auxiliar-vos na planifica" + ccedil + atilde + "o das medidas correctivas e para poderem " + - "apresent" + aacute + "-los em caso de inspec" + ccedil + atilde + "o da ACT – Autoridade para as Condi" + ccedil + otilde + "es do Trabalho." + - "
" + - "
" + - "
" + - "Caso pretendam o nosso apoio ou necessitem de qualquer esclarecimento, contactem-nos, por favor, atrav" + eacute + "s do telefone (+351) 213 504 540." + - "
" + - "
" + - "
" + - "Com os melhores cumprimentos, " + - "
" + - "
" + - "
" + - nomeTecnico + - "
" + - "SIPRP - Sociedade Ib" + eacute + "rica de Preven" + ccedil + atilde + "o de Riscos Profissionais " + - "
" + - "Atrium Saldanha - Pra" + ccedil + "a Duque de Saldanha, 1 - 9º G - 1050-094 Lisboa " + - "
" + - "Telefone: (+351) 213 504 540 " + - "
" + - "Fax: (+351) 213 504 549 " + - "
" + - "E-mail: geral@siprp.pt " + - "
" + - "URL: www.siprp.com " + - "
" + - "
" + - "
" + - "Esta " + eacute + " uma mensagem gerada automaticamente pelo nosso sistema, por favor n" + atilde + "o responda.

"; - MailDialog md = new MailDialog( getFrame(), to, bcc, subject, body, getRelatoriosTemp(relatorio), MailSender.from ); - result = md.wasSent(); - } - return result; - } - - private String getShortNameForEstabelecimento( EstabelecimentosData estabelecimento ) - { - String result = null; - String nome = estabelecimento.getNome_plain(); - if( nome != null ) - { - result = nome.trim(); - if( result.length() > MAX_NOME_ESTABELECIMENTO_ON_FILENAME ) - { - String [] tokens = result.split( " " ); - if( tokens != null && tokens.length > 2 ) - { - result = ""; - for ( String token : tokens ) - { - result += token == null ? "" : token; - } - } - } - } - return result; - } - - private Vector getRelatoriosTemp(HsRelatorioData relatorio) throws Exception - { - Vector result = new Vector(); - byte[] relatorioPDF = new RelatorioPDFCreator().createPDF( relatorio.getId() ); - byte[] planoPDF = new PlanoActuacaoPDFCreator().createPDF( relatorio.getId(), false ); - if( relatorioPDF != null ) - { - String data = relatorio.toMarcacao_id().getData_relatorio() == null ? "" : HsRelatorioData.DATE_FORMAT.format( relatorio.getData() ); - String estabelecimento = getShortNameForEstabelecimento(relatorio.toMarcacao_id().toEstabelecimento_id() ); - File relat = File.createTempFile("Relatorio - " + estabelecimento + " - " + data, ".pdf"); - if( relat != null ) - { - FileOutputStream fos = new FileOutputStream(relat); - fos.write(relatorioPDF); - fos.close(); - result.add( relat ); - } - } - if( planoPDF != null ) - { - String data = relatorio.toMarcacao_id().getData_relatorio() == null ? "" : HsRelatorioData.DATE_FORMAT.format( relatorio.getData() ); - String estabelecimento = relatorio.toMarcacao_id().toEstabelecimento_id().getNome_plain(); - File plan = File.createTempFile("Plano de actuacao - " + estabelecimento + " - " + data, ".pdf"); - if( plan != null ) - { - FileOutputStream fos = new FileOutputStream(plan); - fos.write(planoPDF); - fos.close(); - result.add( plan ); - } - } - return result; - } - - private void save() - { - try - { - if( relatorio != null ) - { - relatorio.setData( dataRelatorio.getDate() ); - relatorio.setAvaliacao_inicial( radioInicial.isSelected() ); - } - relatorio.setAcompanhante1( fieldNome1.getText() ); - relatorio.setAcompanhante2( fieldNome2.getText() ); - - relatorio.setFuncao_acompanhante1(fieldFuncao1.getText()); - relatorio.setFuncao_acompanhante2(fieldFuncao2.getText()); - relatorio.save(); - refresh(); - buttonRevertText.setEnabled( false ); - buttonSave.setEnabled( false ); - } catch( Exception e ) - { - LeafDialog.error(e); - } - } - - private void revert() - { - refresh(); - buttonRevertText.setEnabled( false ); - buttonSave.setEnabled( false ); - } - - private void refresh() - { - dataRelatorio.setDate( relatorio == null ? null : relatorio.getData() ); - if( relatorio == null || relatorio.getAvaliacao_inicial() == null ) - { - bg.clearSelection(); - } - else - { - radioInicial.setSelected( relatorio.getAvaliacao_inicial() ); - radioPeriodica.setSelected( !relatorio.getAvaliacao_inicial() ); - } - String tecnicoName = null; - if(relatorio != null) - { - MarcacoesEstabelecimentoData marcacao = relatorio.toMarcacao_id(); - if( marcacao != null ) - { - MarcacoesTecnicosHstData tecnico = marcacao.toTecnico_hst(); - if( tecnico != null ) - { - tecnicoName = tecnico.getNome(); - } - } - } - fieldTecnico.setText( tecnicoName ); - String tecnicoSuperiorName = null; - if( relatorio != null ) - { - MarcacoesEstabelecimentoData marcacao = relatorio.toMarcacao_id(); - if( marcacao != null ) - { - MarcacoesTecnicosHstData tecnico = marcacao.toTecnico_superior_hst(); - if( tecnico != null ) - { - tecnicoSuperiorName = tecnico.getNome(); - } - } - } - fieldTecnicoSuperior.setText( tecnicoSuperiorName ); - fieldNome1.setText( relatorio == null ? null : relatorio.getAcompanhante1() ); - fieldNome2.setText( relatorio == null ? null : relatorio.getAcompanhante2() ); - fieldFuncao1.setText( relatorio == null ? null : relatorio.getFuncao_acompanhante1() ); - fieldFuncao2.setText( relatorio == null ? null : relatorio.getFuncao_acompanhante2() ); - } - - private void setEnabled() - { - boolean enabled = relatorio != null && relatorio.getIs_submetido() == null; - dataRelatorio.setEnabled( enabled ); - radioInicial.setEnabled( enabled );; - radioPeriodica.setEnabled( enabled ); - fieldTecnico.setEnabled( false ); - fieldTecnicoSuperior.setEnabled( false ); - fieldNome1.setEnabled( enabled ); - fieldNome2.setEnabled( enabled ); - fieldFuncao1.setEnabled( enabled ); - fieldFuncao2.setEnabled( enabled ); - buttonSubmit.setEnabled( enabled ); - buttonPdfPlano.setEnabled( relatorio != null ); - buttonPdfRelatorio.setEnabled( relatorio != null ); - buttonRevertPlano.setEnabled( enabled ); - panelFuncionarios.setEnabled( enabled ); - } - - public void setRelatorio( HsRelatorioData relatorio,boolean create ) - { - this.relatorio = relatorio; - buttonSave.setEnabled( false ); - buttonRevertText.setEnabled( false ); - panelEquipamentos.setRelatorio( relatorio ); - panelPlano.setRelatorio( relatorio ); - panelLegislacao.setRelatorio( relatorio ); - panelNormalizacao.setRelatorio( relatorio ); - panelFuncionarios.setValue( relatorio == null ? null : ( relatorio.getFuncionarios() == null ? DEFAULT_FUNCIONARIOS_TEXT : relatorio.getFuncionarios() ) ); - if( create ) - { - this.revert(false); - } - refresh(); - setEnabled(); - } - - private void updated( EventObject e ) - { - Object source = e.getSource(); - if( source instanceof Component ) - { - if( ( (Component) source).isEnabled() ) - { - buttonSave.setEnabled( true ); - buttonRevertText.setEnabled( true ); - } - } - } - - @Override - public void caretUpdate( CaretEvent e ) - { - updated(e); - } - - @Override - public void stateChanged( ChangeEvent e ) - { - updated(e); - } - - @Override - public void actionPerformed( ActionEvent e ) - { - updated(e); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PlanoActuacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PlanoActuacaoPanel.java deleted file mode 100644 index d468458f..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/PlanoActuacaoPanel.java +++ /dev/null @@ -1,193 +0,0 @@ -package siprp.higiene.relatorio; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.CardLayout; -import java.awt.Dimension; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.BorderFactory; -import javax.swing.JPanel; - -import shst.data.outer.HsRelatorioAreaData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.HsRelatorioPostoData; -import shst.data.outer.HsRelatorioPostoMedidaData; -import shst.data.outer.HsRelatorioPostoRiscoData; -import shst.logic.HigieneSegurancaLogic; - -public class PlanoActuacaoPanel extends JPanel -{ - - private static final long serialVersionUID = 1L; - - private static final String RISCO_PANEL = "RISCO_PANEL"; - - private static final String MEDIDA_PANEL = "MEDIDA_PANEL"; - - private static final String EMPTY_PANEL = "EMPTY_PANEL"; - - private final VerAreasRelatorioPanel areas = new VerAreasRelatorioPanel(); - - private final GerirMedidasRelatorioPanel riscos = new GerirMedidasRelatorioPanel(); - - private final GerirValoresRiscoPanel valoresRisco = new GerirValoresRiscoPanel(); - - private final GerirMedidaRelatorioPanel valoresMedida = new GerirMedidaRelatorioPanel(); - - private final JPanel emptyPanel = new JPanel(); - - private final JPanel valoresPanel = new JPanel(); - - private final CardLayout cards = new CardLayout(); - - private HsRelatorioData relatorio = null; - - public PlanoActuacaoPanel() - { - startupListeners(); - startupComponents(); - startupLayout(); - placeComponents(); - cards.show( valoresPanel, EMPTY_PANEL ); - } - - private void startupListeners() - { - areas.addPropertyChangeListener( VerAreasRelatorioPanel.SELECTION_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - if( evt.getNewValue() instanceof HsRelatorioPostoData ) - { - riscos.setPosto( (HsRelatorioPostoData) evt.getNewValue() ); - } - else - { - riscos.setPosto( null ); - } - } - } ); - riscos.addPropertyChangeListener( GerirMedidasRelatorioPanel.SELECTION_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - if( evt.getNewValue() instanceof HsRelatorioPostoRiscoData ) - { - cards.show( valoresPanel, RISCO_PANEL ); - valoresRisco.setRelatorioPostoRisco( (HsRelatorioPostoRiscoData) evt.getNewValue() ); - } - else if( evt.getNewValue() instanceof HsRelatorioPostoMedidaData ) - { - cards.show( valoresPanel, MEDIDA_PANEL ); - valoresMedida.setMedida( (HsRelatorioPostoMedidaData) evt.getNewValue() ); - } - else - { - cards.show( valoresPanel, EMPTY_PANEL ); - valoresRisco.setRelatorioPostoRisco( null ); - valoresMedida.setMedida( null ); - } - } - } ); - valoresRisco.addPropertyChangeListener( GerirValoresRiscoPanel.VALUE_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - riscos.repaint(); - areas.repaint(); - } - } ); - valoresMedida.addPropertyChangeListener( GerirMedidaRelatorioPanel.MEDIDA_CHANGED, new PropertyChangeListener() - { - @Override - public void propertyChange( PropertyChangeEvent evt ) - { - riscos.refresh(); - } - } ); - } - - private void startupComponents() - { - riscos.setBorder( BorderFactory.createTitledBorder( "Riscos" ) ); - areas.setBorder( BorderFactory.createTitledBorder( "Postos de trabalho" ) ); - areas.setPreferredSize( new Dimension(250,0) ); - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( - new double[]{ TableLayout.MINIMUM, TableLayout.PREFERRED, TableLayout.FILL, TableLayout.FILL }, - new double[]{ TableLayout.MINIMUM, TableLayout.FILL } - ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - valoresPanel.setLayout(cards); - } - - private void placeComponents() - { - valoresPanel.add( valoresRisco, RISCO_PANEL ); - valoresPanel.add( valoresMedida, MEDIDA_PANEL ); - valoresPanel.add( emptyPanel, EMPTY_PANEL ); - add( areas, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - add( riscos, new TableLayoutConstraints( 2, 1 ) ); - add( valoresPanel, new TableLayoutConstraints( 3, 1 ) ); - } - - public void setRelatorio( HsRelatorioData relatorio ) - { - this.relatorio = relatorio; - areas.setRelatorio( relatorio ); - riscos.setPosto( null ); - valoresRisco.setRelatorioPostoRisco( null ); - valoresRisco.setEnabled( relatorio != null && relatorio.getIs_submetido() == null ); - valoresMedida.setMedida( null ); - valoresMedida.setEnabled( relatorio != null && relatorio.getIs_submetido() == null ); - } - - public boolean isValidPlano() - { - boolean result = true; - if( relatorio != null ) - { - for( HsRelatorioAreaData area : relatorio.fromHsRelatorioArea_relatorio_id() ) - { - for( HsRelatorioPostoData posto : area.fromHsRelatorioPosto_area_id() ) - { - for( HsRelatorioPostoRiscoData relRisco : posto.fromHsRelatorioPostoRisco_posto_id() ) - { - boolean preenchido = relRisco.toValor_qualitativo_id() != null; - if( !preenchido ) - { - preenchido = HigieneSegurancaLogic.isProbabilidadeValida( relRisco.getProbabilidade() ) && HigieneSegurancaLogic.isSeveridadeValida( relRisco.getSeveridade() ); - } - if( !preenchido ) - { - result = false; - break; - } - } - if( !result ) - { - break; - } - } - if( !result ) - { - break; - } - } - } - return result; - } - -} - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioHigieneSegurancaWindow.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioHigieneSegurancaWindow.java deleted file mode 100644 index 895190be..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioHigieneSegurancaWindow.java +++ /dev/null @@ -1,246 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Color; -import java.awt.Container; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.Date; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.SwingUtilities; - -import leaf.ui.LeafDialog; -import shst.data.outer.EmpresasData; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.MarcacoesEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.tracker.TrackableWindow; - -public class RelatorioHigieneSegurancaWindow extends SIPRPFrame implements TrackableWindow -{ - private static final long serialVersionUID = 1L; - - public static final Color COLOR_RISCO_OK = new Color(200,255,200); - - public static final Color COLOR_RISCO_OK_SEL = new Color(140,240,140); - - public static final Color COLOR_MEDIDA_OK = new Color(200,230,255); - - public static final Color COLOR_MEDIDA_OK_SEL = new Color(160,190,255); - - public static final String TITLE = "Relat" + oacute + "rios de H&S"; - - public static final Dimension SIZE = new Dimension( 1024, 700 ); - - private final JComboBox comboEmpresas = new JComboBox(); - - private final JComboBox comboEstabelecimentos = new JComboBox(); - - private final JComboBox comboVisitas = new JComboBox(); - - private final PanelRelatorio panelRelatorio = new PanelRelatorio(); - - public RelatorioHigieneSegurancaWindow() - { - setupListeners(); - startupComponents(); - startupLayout(); - placeComponents(); - setTitle( TITLE ); - setSize( SIZE ); - setLocationRelativeTo( null ); - } - - private void startupComponents() - { - panelRelatorio.setBorder( BorderFactory.createTitledBorder( "Relat" + oacute + "rio" ) ); - for( EmpresasData empresa : HigieneSegurancaLogic.getAllEmpresas() ) - { - comboEmpresas.addItem( empresa ); - } - } - - private void startupLayout() - { - TableLayout layout = new TableLayout( - new double[]{ TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.FILL }, - new double[]{ TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL } - ); - layout.setVGap( 5 ); - layout.setHGap( 5 ); - getContentPane().setLayout( layout ); - } - - private void placeComponents() - { - Container pane = getContentPane(); - pane.add( new JLabel("Empresa"), new TableLayoutConstraints( 0, 0 ) ); - pane.add( comboEmpresas, new TableLayoutConstraints( 1, 0, 3, 0 ) ); - pane.add( new JLabel("Estabelecimento"), new TableLayoutConstraints( 0, 1 ) ); - pane.add( comboEstabelecimentos, new TableLayoutConstraints( 1, 1 ) ); - pane.add( new JLabel("Visita"), new TableLayoutConstraints( 2, 1 ) ); - pane.add( comboVisitas, new TableLayoutConstraints( 3, 1 ) ); - pane.add( panelRelatorio, new TableLayoutConstraints(0,2,3,2)); - } - - private void setupListeners() - { - comboEmpresas.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - if( e.getStateChange() == ItemEvent.SELECTED ) - { - fillEstabelecimentos( (EmpresasData) e.getItem() ); - } - } - } ); - comboEstabelecimentos.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - if( e.getStateChange() == ItemEvent.SELECTED ) - { - fillVisitas( (EstabelecimentosData) e.getItem() ); - } - } - } ); - comboVisitas.addItemListener( new ItemListener() - { - @Override - public void itemStateChanged( ItemEvent e ) - { - if( e.getStateChange() == ItemEvent.SELECTED ) - { - fillRelatorio( (MarcacoesEstabelecimentoData) e.getItem() ); - } - } - } ); - - } - - private void fillEstabelecimentos( EmpresasData empresa ) - { - comboEstabelecimentos.removeAllItems(); - if( empresa != null ) - { - for( EstabelecimentosData estabelecimento : empresa.fromEstabelecimentos_empresa_id() ) - { - comboEstabelecimentos.addItem( estabelecimento ); - } - } - } - - private void fillVisitas( EstabelecimentosData estabelecimento ) - { - comboVisitas.removeAllItems(); - if( estabelecimento != null ) - { - for( MarcacoesEstabelecimentoData visita : estabelecimento.fromMarcacoesEstabelecimento_estabelecimento_id() ) - { - if( "y".equals( visita.getRealizada() ) ) - { - comboVisitas.addItem( visita ); - } - } - } - } - - private void fillRelatorio( MarcacoesEstabelecimentoData visita ) - { - try - { - setCursor( new Cursor( Cursor.WAIT_CURSOR ) ); - boolean carregarDadosEstabelecimento = false; -// panelRelatorio.setRelatorio( null, carregarDadosEstabelecimento ); - if( visita != null ) - { - HsRelatorioData relatorio = null; - List< HsRelatorioData > relatorios = visita.fromHsRelatorio_marcacao_id(); - Date data = null; - for( HsRelatorioData current : relatorios ) - { - boolean newest = data == null ? true : ( data.before( current.getData() ) ); - if( newest ) - { - data = current.getData(); - relatorio = current; - } - } - if( relatorio == null ) - { - relatorio = new HsRelatorioData(); - relatorio.setData( new Date() ); - relatorio.setToMarcacao_id( visita ); - relatorio.save(); - carregarDadosEstabelecimento = true; - } - panelRelatorio.setRelatorio( relatorio, carregarDadosEstabelecimento );; - } - else - { - panelRelatorio.setRelatorio( null, carregarDadosEstabelecimento ); - } - } - catch( Exception e ) - { - LeafDialog.error(e); - } - finally - { - setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) ); - } - } - - @Override - public void open() - { - setVisible( true ); - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable() - { - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - @Override - public boolean closeIfPossible() - { - close(); - return true; - } - - @Override - public void refresh() - { - - } - - public static void main( String[] args ) - { - RelatorioHigieneSegurancaWindow window = new RelatorioHigieneSegurancaWindow(); - window.setVisible( true ); - window.setDefaultCloseOperation( SIPRPFrame.EXIT_ON_CLOSE ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioLegislacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioLegislacaoPanel.java deleted file mode 100644 index a2d5dd48..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioLegislacaoPanel.java +++ /dev/null @@ -1,117 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Collections; -import java.util.List; -import java.util.Vector; - -import javax.swing.JButton; - -import leaf.ui.SimpleTable; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.HsRelatorioLegislacaoData; -import shst.data.outer.MarcacoesEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; - -import com.evolute.swing.panel.EvoPanel; -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.tables.ColumnizedObjectArray; - -public class RelatorioLegislacaoPanel extends EvoPanel -{ - private static final long serialVersionUID = 1L; - - private final JButton revert = new JButton("Reverter"); - - private HsRelatorioData relatorio = null; - - private final SimpleTable table = new SimpleTable( "Categoria", "Legisla" + ccedil + atilde + "o" ); - - public RelatorioLegislacaoPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - } - - private void startupComponents() - { - table.getTable().fixColumnWidth(0,200); - revert.addActionListener( new ActionListener() - { - - @Override - public void actionPerformed( ActionEvent e ) - { - runAsynchronously( new Runnable() - { - @Override - public void run() - { - if( relatorio != null ) - { - MarcacoesEstabelecimentoData marcacao = relatorio.toMarcacao_id(); - if( marcacao != null ) - { - EstabelecimentosData estabelecimento = marcacao.toEstabelecimento_id(); - if( estabelecimento != null ) - { - try - { - HigieneSegurancaLogic.reverterLegislacao( relatorio, estabelecimento, true ); - } catch( Exception e1 ) - { - ErrorLogger.logException( e1 ); - } - } - } - refresh(); - } - } - } ); - } - } ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[]{ TableLayout.MINIMUM, TableLayout.FILL }, new double[]{ TableLayout.MINIMUM, TableLayout.FILL } ); - this.setLayout( layout ); - } - - private void placeComponents() - { - this.add( table, new TableLayoutConstraints( 0, 1,1,1 ) ); - this.add( revert, new TableLayoutConstraints( 0, 0 ) ); - } - - public void setRelatorio( HsRelatorioData relatorio ) - { - this.relatorio = relatorio; - refresh(); - } - - private void refresh() - { - table.clear(); - if( relatorio != null ) - { - List legislacoes = relatorio.fromHsRelatorioLegislacao_hs_relatorio_id(); - Collections.sort( legislacoes ); - Vector rows = new Vector(); - for( HsRelatorioLegislacaoData legislacao : legislacoes ) - { - rows.add( new ColumnizedObjectArray( new Object[]{ legislacao, legislacao.getCategoria(), legislacao.getDescricao() }, true ) ); - } - table.setRows( rows ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioNormalizacaoPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioNormalizacaoPanel.java deleted file mode 100644 index 4b6b0889..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/RelatorioNormalizacaoPanel.java +++ /dev/null @@ -1,120 +0,0 @@ -package siprp.higiene.relatorio; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import static com.evolute.utils.strings.UnicodeLatin1Map.oacute; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Collections; -import java.util.List; -import java.util.Vector; - -import javax.swing.JButton; - -import leaf.ui.SimpleTable; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.HsRelatorioNormalizacaoData; -import shst.data.outer.MarcacoesEstabelecimentoData; -import shst.logic.HigieneSegurancaLogic; - -import com.evolute.swing.panel.EvoPanel; -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.tables.ColumnizedObjectArray; - -public class RelatorioNormalizacaoPanel extends EvoPanel -{ - - private static final long serialVersionUID = 1L; - - private HsRelatorioData relatorio = null; - - private final JButton revert = new JButton("Reverter"); - - private final SimpleTable table = new SimpleTable( "C" + oacute + "digo", "Normaliza" + ccedil + atilde + "o", "" ); - - public RelatorioNormalizacaoPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - } - - private void startupComponents() - { - table.getTable().fixColumnWidth(0,50); - table.getTable().fixColumnWidth(2,100); - revert.addActionListener( new ActionListener() - { - - @Override - public void actionPerformed( ActionEvent e ) - { - runAsynchronously( new Runnable() - { - @Override - public void run() - { - if( relatorio != null ) - { - MarcacoesEstabelecimentoData marcacao = relatorio.toMarcacao_id(); - if( marcacao != null ) - { - EstabelecimentosData estabelecimento = marcacao.toEstabelecimento_id(); - if( estabelecimento != null ) - { - try - { - HigieneSegurancaLogic.reverterNormalizacao( relatorio, estabelecimento, true ); - } catch( Exception e1 ) - { - ErrorLogger.logException( e1 ); - } - } - } - refresh(); - } - } - } ); - } - } ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( new double[]{ TableLayout.MINIMUM, TableLayout.FILL }, new double[]{ TableLayout.MINIMUM, TableLayout.FILL } ); - this.setLayout( layout ); - } - - private void placeComponents() - { - this.add( table, new TableLayoutConstraints( 0, 1,1,1 ) ); - this.add( revert, new TableLayoutConstraints( 0, 0 ) ); - } - - public void setRelatorio( HsRelatorioData relatorio ) - { - this.relatorio = relatorio; - refresh(); - } - - private void refresh() - { - table.clear(); - if( relatorio != null ) - { - List normalizacoes = relatorio.fromHsRelatorioNormalizacao_hs_relatorio_id(); - Collections.sort( normalizacoes ); - Vector rows = new Vector(); - for( HsRelatorioNormalizacaoData normalizacao : normalizacoes ) - { - rows.add( new ColumnizedObjectArray( new Object[]{ normalizacao, normalizacao.getCodigo(), normalizacao.getDescricao(), normalizacao.getPortuguesa() ? "Portuguesa" : "Internacional" }, true ) ); - } - table.setRows( rows ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/VerAreasRelatorioPanel.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/VerAreasRelatorioPanel.java deleted file mode 100644 index e6d9bfa8..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/VerAreasRelatorioPanel.java +++ /dev/null @@ -1,202 +0,0 @@ -package siprp.higiene.relatorio; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import leaf.ui.LeafTree; -import shst.data.outer.HsRelatorioAreaData; -import shst.data.outer.HsRelatorioData; -import shst.data.outer.HsRelatorioPostoData; -import shst.data.outer.HsRelatorioPostoRiscoData; -import shst.logic.HigieneSegurancaLogic; -import shst.logic.node.PostoRelatorioNode; - -import com.evolute.utils.error.ErrorLogger; -import com.evolute.utils.images.ImageIconLoader; -import com.evolute.utils.ui.trees.TreeTools; - -public class VerAreasRelatorioPanel extends JPanel -{ - - private static final long serialVersionUID = 1L; - - public static final String SELECTION_CHANGED = "SELECTION_CHANGED"; - - private final JButton buttonEdit = new JButton( "Editar Nome", ImageIconLoader.loadImageIconSilent( "siprp/higiene/relatorio/edit.png" ) ); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - - private final DefaultTreeModel model = new DefaultTreeModel( root ); - - public final LeafTree tree = new LeafTree( model ); - - private final JScrollPane scroll = new JScrollPane( tree ); - - private HsRelatorioData relatorio = null; - - private DefaultMutableTreeNode selectedNode = null; - - public VerAreasRelatorioPanel() - { - startupComponents(); - setupLayout(); - placeComponents(); - startupListeners(); - } - - private void startupComponents() - { - buttonEdit.setEnabled( false ); - tree.setRootVisible( false ); - tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); - tree.setCellRenderer(new DefaultTreeCellRenderer() - { - - private static final long serialVersionUID = 1L; - - @Override - public Component getTreeCellRendererComponent( JTree pTree, Object pValue, boolean pIsSelected, boolean pIsExpanded, boolean pIsLeaf, int pRow, boolean pHasFocus ) - { - super.getTreeCellRendererComponent( pTree, pValue, pIsSelected, pIsExpanded, pIsLeaf, pRow, pHasFocus ); - boolean highlight= false; - Color highColor = null; - Color lowColor = null; - if( pValue instanceof PostoRelatorioNode ) - { - Object userObject = ((PostoRelatorioNode)pValue).getUserObject(); - if( userObject instanceof HsRelatorioPostoData ) - { - HsRelatorioPostoData posto = (HsRelatorioPostoData) userObject; - boolean allOk = true; - for( HsRelatorioPostoRiscoData rel : posto.fromHsRelatorioPostoRisco_posto_id() ) - { - if( rel.toRisco_id().getDeleted_date() == null ) - { - allOk &= HigieneSegurancaLogic.isRelatorioRiscoPreenchido( rel ); - } - } - highColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK_SEL; - lowColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK; - highlight = allOk; - } - } - if( highlight ) - { - setOpaque( true ); - setBackground( pIsSelected ? highColor : lowColor ); - } - else - { - setOpaque( false ); - } - return this; - } - } ); - TreeTools.registerTreeKeepExpandState( tree ); - } - - private void setupLayout() - { - TableLayout layout = new TableLayout( - new double[]{ TableLayout.MINIMUM, TableLayout.FILL }, - new double[]{ TableLayout.MINIMUM, TableLayout.FILL } - ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - setLayout( layout ); - } - - private void placeComponents() - { - add( buttonEdit, new TableLayoutConstraints( 0, 0 ) ); - add( scroll, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - } - - private void startupListeners() - { - - tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener(){ - @Override - public void valueChanged( TreeSelectionEvent e ) - { - TreePath path = tree.getSelectionPath(); - Object object = path == null ? null : path.getLastPathComponent(); - HsRelatorioPostoData posto = object == null ? null : ( (object instanceof PostoRelatorioNode) ? (HsRelatorioPostoData) ((PostoRelatorioNode) object).getUserObject() : null); - selectedNode = (object instanceof DefaultMutableTreeNode) ? (DefaultMutableTreeNode) object : null; - buttonEdit.setEnabled( selectedNode != null ); - firePropertyChange( SELECTION_CHANGED, null, posto ); - } - } ); - - buttonEdit.addActionListener( new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - Object object = selectedNode == null ? null : selectedNode.getUserObject(); - if( object != null ) - { - String title = "Editar nome"; - String result = (String) JOptionPane.showInputDialog( VerAreasRelatorioPanel.this, "", title, JOptionPane.QUESTION_MESSAGE, null, null, object.toString() ); - if( result != null && ! result.trim().isEmpty() ) - { - try - { - if( object instanceof HsRelatorioAreaData ) - { - ( ( HsRelatorioAreaData ) object ).setDescription( result ); - ( ( HsRelatorioAreaData ) object ).save(); - refresh(); - } - else if( object instanceof HsRelatorioPostoData ) - { - ( ( HsRelatorioPostoData ) object ).setDescription( result ); - ( ( HsRelatorioPostoData ) object ).save(); - refresh(); - } - } - catch( Exception ex ) - { - ErrorLogger.logException( ex ); - } - } - } - } - } ); - } - - public void refresh() - { - root.removeAllChildren(); - if( relatorio != null ) - { - TreeTools.merge( root, HigieneSegurancaLogic.getAreasRelatorioTree( relatorio ) ); - } - TreeTools.refreshTree( tree, root, false ); - } - - public void setRelatorio( HsRelatorioData relatorio ) - { - this.relatorio = relatorio; - refresh(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/adobe_reader.png b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/adobe_reader.png deleted file mode 100644 index 613bda10..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/adobe_reader.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/edit.png b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/edit.png deleted file mode 100644 index ae851759..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/edit.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/AreaToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/AreaToPrint.java deleted file mode 100644 index b861ac48..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/AreaToPrint.java +++ /dev/null @@ -1,59 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - -public class AreaToPrint - implements PrintableInterface, Comparable< Object > -{ - protected String designacao; - protected Vector postos; - protected Integer ordem; - protected boolean temGenerico; - - public AreaToPrint( String designacao, Vector postos, Integer ordem, boolean temGenerico ) - { - super(); - this.designacao = designacao; - this.postos = postos; - this.ordem = ordem; - this.temGenerico = temGenerico; - } - - @Override - public Element toJdomElement() throws Exception - { - Element areaElement = new Element( "area" ); - Element designacaoElement = new Element( "designacao" ); - designacaoElement.setText( designacao ); - areaElement.addContent( designacaoElement ); - for( PostoToPrint posto : postos ) - { - areaElement.addContent( posto.toJdomElement() ); - } - return areaElement; - } - - @Override - public int compareTo(Object o) - { - if( o instanceof AreaToPrint ) - { - if( temGenerico && !( ( AreaToPrint ) o ).temGenerico ) - { - return -1; - } - else if( !temGenerico && ( ( AreaToPrint ) o ).temGenerico ) - { - return 1; - } - if( ordem != null ) - { - return ( ( ( AreaToPrint ) o ).ordem == null ) ? -1 : ordem.compareTo( ( ( AreaToPrint ) o ).ordem ); - } - } - return 0; - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DBConstants.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DBConstants.java deleted file mode 100644 index 06e1a1fa..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DBConstants.java +++ /dev/null @@ -1,17 +0,0 @@ -package siprp.higiene.relatorio.print; - -public interface DBConstants -{ - -// public static final String LOCAL_URL = "jdbc:postgresql://localhost:5436/siprp_local_3"; -//// public static final String LOCAL_URL = "jdbc:postgresql://storage/siprp_local"; -// public static final String LOCAL_USER = "postgres"; -//// public static final String LOCAL_PASSWORD = "Typein"; -// public static final String LOCAL_PASSWORD = null; - - public static final String LOCAL_URL = "jdbc:postgresql://www.evolute.pt:5436/siprp_local_3"; - public static final String LOCAL_USER = "postgres"; - public static final String LOCAL_PASSWORD = "Typein"; - - public static final String LOCAL_DBMANAGER = "LOCAL DBMANAGER"; -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DataToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DataToPrint.java deleted file mode 100644 index b921677b..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/DataToPrint.java +++ /dev/null @@ -1,66 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Calendar; -import java.util.Date; - -import org.jdom.Element; - -import com.evolute.utils.date.DateUtils; - -public class DataToPrint - implements PrintableInterface -{ - protected String tag; - protected Date data; - - public DataToPrint( String tag, Date data ) - { - super(); - this.tag = tag; - this.data = data; - } - - @Override - public Element toJdomElement() throws Exception - { - Element dataElement = new Element( tag ); - Calendar cal = Calendar.getInstance(); - cal.setTime( data ); - int ano = cal.get( Calendar.YEAR ); - int mes = cal.get( Calendar.MONTH ); - int dia = cal.get( Calendar.DAY_OF_MONTH ); - Element anoElement = new Element( "ano" ); - anoElement.setText( "" + ano ); - dataElement.addContent( anoElement ); - Element mesElement = new Element( "mes" ); - mesElement.setText( "" + ( mes + 1 ) ); - dataElement.addContent( mesElement ); - Element mesExtensoElement = new Element( "mes-extenso" ); - mesExtensoElement.setText( DateUtils.MONTHS_FULL_PT[ mes ] ); - dataElement.addContent( mesExtensoElement ); - Element diaElement = new Element( "dia" ); - diaElement.setText( "" + dia ); - dataElement.addContent( diaElement ); - return dataElement; - } - - public String getTag() - { - return tag; - } - - public void setTag( String tag ) - { - this.tag = tag; - } - - public Date getData() - { - return data; - } - - public void setData( Date data ) - { - this.data = data; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EmpresaToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EmpresaToPrint.java deleted file mode 100644 index 3786ebd9..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EmpresaToPrint.java +++ /dev/null @@ -1,76 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public class EmpresaToPrint - implements PrintableInterface -{ - protected String designacaoSocial; - protected String logotipo; - protected String estabelecimento; - protected String actividade; - protected String nomeAcompanhante; - protected String funcaoAcompanhante; - protected String nomeAcompanhante2; - protected String funcaoAcompanhante2; - protected String morada; - - public EmpresaToPrint( String designacaoSocial, String logotipo, - String estabelecimento, String actividade, String nomeAcompanhante, - String funcaoAcompanhante, String nomeAcompanhante2, - String funcaoAcompanhante2, String morada ) - { - super(); - this.designacaoSocial = designacaoSocial; - this.logotipo = logotipo; - this.estabelecimento = estabelecimento; - this.actividade = actividade; - this.nomeAcompanhante = nomeAcompanhante; - this.funcaoAcompanhante = funcaoAcompanhante; - this.nomeAcompanhante2 = nomeAcompanhante2; - this.funcaoAcompanhante2 = funcaoAcompanhante2; - this.morada = morada; - } - - - @Override - public Element toJdomElement() throws Exception - { - Element empresaElement = new Element( "empresa" ); - Element designacaoSocialElement = new Element( "designacao-social" ); - designacaoSocialElement.setText( designacaoSocial ); - empresaElement.addContent( designacaoSocialElement ); - Element logotipoElement = new Element( "logotipo" ); - logotipoElement.setText( logotipo ); - empresaElement.addContent( logotipoElement ); - Element estabelecimentoElement = new Element( "estabelecimento" ); - estabelecimentoElement.setText( estabelecimento ); - empresaElement.addContent( estabelecimentoElement ); - Element actividadeElement = new Element( "actividade" ); - actividadeElement.setText( actividade ); - empresaElement.addContent( actividadeElement ); - Element nomeAcompanhanteElement = new Element( "nome-acompanhante" ); - nomeAcompanhanteElement.setText( nomeAcompanhante ); - empresaElement.addContent( nomeAcompanhanteElement ); - Element funcaoAcompanhanteElement = new Element( "funcao-acompanhante" ); - funcaoAcompanhanteElement.setText( funcaoAcompanhante ); - empresaElement.addContent( funcaoAcompanhanteElement ); - if( nomeAcompanhante2 != null && nomeAcompanhante2.trim().length() > 0 ) - { - Element nomeAcompanhante2Element = new Element( "nome-acompanhante2" ); - nomeAcompanhante2Element.setText( nomeAcompanhante2 ); - empresaElement.addContent( nomeAcompanhante2Element ); - Element funcaoAcompanhante2Element = new Element( "funcao-acompanhante2" ); - funcaoAcompanhante2Element.setText( funcaoAcompanhante2 ); - empresaElement.addContent( funcaoAcompanhante2Element ); - } - if( morada != null ) - { - Element moradaElement = new Element( "morada" ); - moradaElement.setText( morada ); - empresaElement.addContent( moradaElement ); - } - return empresaElement; - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentoToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentoToPrint.java deleted file mode 100644 index bd2785b4..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentoToPrint.java +++ /dev/null @@ -1,27 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public class EquipamentoToPrint - implements PrintableInterface -{ - protected String tipo; - protected String marca; - protected String modelo; - - public EquipamentoToPrint( String tipo, String marca, String modelo ) - { - super(); - this.tipo = tipo; - this.marca = marca; - this.modelo = modelo; - } - - @Override - public Element toJdomElement() throws Exception - { - Element equipamentoElement = new Element( "equipamento" ); - equipamentoElement.setText( tipo + " (" + marca + " " + modelo + ")" ); - return equipamentoElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentosToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentosToPrint.java deleted file mode 100644 index 7323db41..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/EquipamentosToPrint.java +++ /dev/null @@ -1,27 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public class EquipamentosToPrint - implements PrintableInterface -{ - protected EquipamentoToPrint equipamentos[]; - - public EquipamentosToPrint( EquipamentoToPrint[] equipamentos ) - { - super(); - this.equipamentos = equipamentos; - } - - @Override - public Element toJdomElement() - throws Exception - { - Element equipamentosElement = new Element( "equipamentos" ); - for( EquipamentoToPrint equipamento : equipamentos ) - { - equipamentosElement.addContent( equipamento.toJdomElement() ); - } - return equipamentosElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/LegislacaoAplicavelToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/LegislacaoAplicavelToPrint.java deleted file mode 100644 index 3861186d..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/LegislacaoAplicavelToPrint.java +++ /dev/null @@ -1,53 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - -public class LegislacaoAplicavelToPrint - implements PrintableInterface -{ - protected Vector diplomasGerais; - protected String[] nomesGruposEspecificos; - protected Vector[] diplomasEspecificos; - - public LegislacaoAplicavelToPrint( Vector diplomasGerais, - String[] nomesGruposEspecificos, Vector[] diplomasEspecificos ) - { - super(); - this.diplomasGerais = diplomasGerais; - this.nomesGruposEspecificos = nomesGruposEspecificos; - this.diplomasEspecificos = diplomasEspecificos; - } - - @Override - public Element toJdomElement() throws Exception - { - Element legislacaoAplicavelElement = new Element( "legislacao-aplicavel" ); - Element legislacaoGeralElement = new Element( "legislacao-geral" ); - for( String diploma : diplomasGerais ) - { - Element diplomaElement = new Element( "diploma" ); - diplomaElement.setText( diploma ); - legislacaoGeralElement.addContent( diplomaElement ); - } - legislacaoAplicavelElement.addContent( legislacaoGeralElement ); - - for( int e = 0; e < nomesGruposEspecificos.length; e++ ) - { - Element legislacaoEspecificaElement = new Element( "legislacao-especifica" ); - Element designacaoElement = new Element( "designacao" ); - designacaoElement.setText( nomesGruposEspecificos[ e ] ); - legislacaoEspecificaElement.addContent( designacaoElement ); - for( String diploma : diplomasEspecificos[ e ] ) - { - Element diplomaElement = new Element( "diploma" ); - diplomaElement.setText( diploma ); - legislacaoEspecificaElement.addContent( diplomaElement ); - } - legislacaoAplicavelElement.addContent( legislacaoEspecificaElement ); - } - return legislacaoAplicavelElement; - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/MedidaToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/MedidaToPrint.java deleted file mode 100644 index 374aecd6..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/MedidaToPrint.java +++ /dev/null @@ -1,30 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public class MedidaToPrint - implements PrintableInterface -{ - protected String requisitosLegais; - protected String descricao; - - public MedidaToPrint( String requisitosLegais, String descricao ) - { - super(); - this.requisitosLegais = requisitosLegais; - this.descricao = descricao; - } - - @Override - public Element toJdomElement() throws Exception - { - Element medidaElement = new Element( "medida" ); - Element requisitosLegaisElement = new Element( "requisitos-legais" ); - requisitosLegaisElement.setText( requisitosLegais ); - medidaElement.addContent( requisitosLegaisElement ); - Element descricaoElement = new Element( "descricao" ); - descricaoElement.setText( descricao ); - medidaElement.addContent( descricaoElement ); - return medidaElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/NormalizacaoToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/NormalizacaoToPrint.java deleted file mode 100644 index c3746d1d..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/NormalizacaoToPrint.java +++ /dev/null @@ -1,43 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - -public class NormalizacaoToPrint - implements PrintableInterface -{ - protected Vector normasPortuguesas; - protected Vector normasInternacionais; - - public NormalizacaoToPrint( Vector normasPortuguesas, Vector normasInternacionais ) - { - super(); - this.normasPortuguesas = normasPortuguesas; - this.normasInternacionais = normasInternacionais; - } - - @Override - public Element toJdomElement() throws Exception - { - Element normalizacaoElement = new Element( "normalizacao-aplicavel" ); - Element portuguesaElement = new Element( "normalizacao-portuguesa" ); - addNormas( portuguesaElement, normasPortuguesas ); - normalizacaoElement.addContent( portuguesaElement ); - Element internacionalElement = new Element( "normalizacao-internacional" ); - addNormas( internacionalElement, normasInternacionais ); - normalizacaoElement.addContent( internacionalElement ); - return normalizacaoElement; - } - - protected void addNormas( Element element, Vector normas ) - { - for( String norma : normas ) - { - Element normaElement = new Element( "norma" ); - normaElement.setText( norma ); - element.addContent( normaElement ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PostoToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PostoToPrint.java deleted file mode 100644 index f8762d9a..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PostoToPrint.java +++ /dev/null @@ -1,41 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - - -public class PostoToPrint - implements PrintableInterface -{ - protected String designacao; - protected Vector riscos; - protected boolean generico; - - public PostoToPrint( String designacao, Vector riscos, boolean generico ) - { - this.designacao = designacao; - this.riscos = riscos; - this.generico = generico; - } - - @Override - public Element toJdomElement() - throws Exception - { - Element postoElement = new Element( "posto" ); - Element designacaoElement = new Element( "designacao" ); - designacaoElement.setText( designacao ); - postoElement.addContent( designacaoElement ); - for( RiscoToPrint risco : riscos ) - { - postoElement.addContent( risco.toJdomElement() ); - } - return postoElement; - } - - public boolean isGenerico() - { - return generico; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PrintableInterface.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PrintableInterface.java deleted file mode 100644 index 3e21c8a4..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/PrintableInterface.java +++ /dev/null @@ -1,8 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public interface PrintableInterface -{ - public Element toJdomElement() throws Exception; -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioDBInit.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioDBInit.java deleted file mode 100644 index b06320cd..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioDBInit.java +++ /dev/null @@ -1,29 +0,0 @@ -package siprp.higiene.relatorio.print; - -import com.evolute.utils.Singleton; -import com.evolute.utils.db.keyretrievers.PostgresqlAutoKeyRetriever; -import com.evolute.utils.sql.Insert; -import com.evolute.utils.strings.UnicodeChecker; - -public class RelatorioDBInit -{ - public static void initDB() - throws Exception - { -// if( web ) -// { -// String url = DBConstants.LOCAL_URL; -// String user = DBConstants.LOCAL_USER; -// String pwd = DBConstants.LOCAL_PASSWORD; -// DBManager localManager = new JDBCManager( url, user, pwd, 10, 8, 8, null ); -// Singleton.setInstance( DBConstants.LOCAL_DBMANAGER, localManager ); -// } -// else -// { - Singleton.setInstance( DBConstants.LOCAL_DBMANAGER, Singleton.getInstance( Singleton.DEFAULT_DBMANAGER ) ); -// } - - Insert.setDefaultKeyRetriever( PostgresqlAutoKeyRetriever.RETRIEVER ); - UnicodeChecker.setUseDoubleSlash( true ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPDFCreator.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPDFCreator.java deleted file mode 100644 index be2e3e21..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPDFCreator.java +++ /dev/null @@ -1,54 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; - -import org.jdom.Document; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; - -import shst.util.fop.PDFCreator; -import siprp.Main; - -import com.evolute.utils.xml.XSLTransformer; - - -public class RelatorioPDFCreator -{ - - public byte[] createPDF( Integer relatorioId ) throws Exception - { - RelatorioToPrint relatorio = RelatorioPrintDataProvider.getProvider().getRelatorioToPrint( relatorioId ); - Document foDoc = new Document( relatorio.toJdomElement() ); - XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); - ByteArrayOutputStream foBaos = new ByteArrayOutputStream(); -// FileOutputStream fos = new FileOutputStream("/home/jneto/a.xml"); - outputter.output( foDoc, foBaos ); -// outputter.output( foDoc, fos ); - -// System.out.println( new String( foBaos.toByteArray() ) ); - byte fo[] = applyTemplate( - getClass().getClassLoader().getResourceAsStream( "siprp/higiene/relatorio/print/relatorio.xsl" ), - new ByteArrayInputStream( foBaos.toByteArray() ) - ); -// System.out.println( new String( fo ) ); - - - //FIXME: FOP COPIADO - PDFCreator.setUserConfig(Main.fopConfigFile); - PDFCreator pdfCreator = PDFCreator.getPDFCreator(); - - - byte pdf[] = pdfCreator.createPdfFromFo( fo ); - return pdf; - } - - public byte[] applyTemplate( InputStream xsl, InputStream dataStream ) throws Exception - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - XSLTransformer.getXSLTransformer().transform( dataStream, xsl, baos ); - return baos.toByteArray(); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPrintDataProvider.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPrintDataProvider.java deleted file mode 100644 index b86fc00d..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioPrintDataProvider.java +++ /dev/null @@ -1,646 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.Vector; - -import siprp.planoactuacao.db.DBConstants; - -import com.evolute.utils.Singleton; -import com.evolute.utils.arrays.Virtual2DArray; -import com.evolute.utils.data.Mappable; -import com.evolute.utils.data.MappableObject; -import com.evolute.utils.db.DBManager; -import com.evolute.utils.db.Executer; -import com.evolute.utils.sql.BlobUpdate; -import com.evolute.utils.sql.Expression; -import com.evolute.utils.sql.Field; -import com.evolute.utils.sql.Select; -import com.evolute.utils.sql.Select2; - - -public class RelatorioPrintDataProvider -{ - private static final Object LOCK = new Object(); - protected static final Object UNCONTROLLED = "Incontrolado"; - protected static final Object CONTROLLED = "Controlado"; - protected static final Object INDETERMINATE = "Indeterminado"; - protected static final Object NAO_VALORAVEL = "N\u00E3o Valor\u00E1vel"; - - private static RelatorioPrintDataProvider instance = null; - - protected final Executer EXECUTER; - - public RelatorioPrintDataProvider() - throws Exception - { - if( Singleton.getInstance( DBConstants.LOCAL_DBMANAGER ) == null ) - { - RelatorioDBInit.initDB(); - } - DBManager LOCAL_DBMANAGER = ( DBManager ) Singleton.getInstance( DBConstants.LOCAL_DBMANAGER ); - EXECUTER = LOCAL_DBMANAGER.getSharedExecuter( this ); - } - - public static RelatorioPrintDataProvider getProvider() - throws Exception - { - synchronized( LOCK ) - { - if( instance == null ) - { - instance = new RelatorioPrintDataProvider(); - } - } - return instance; - } - - public boolean empresaUsaPlanoAlargadoPorPlanoId( Integer planoId ) - throws Exception - { - try - { - Select select = - new Select2( - new String[]{ "hs_relatorio", "marcacoes_estabelecimento", "estabelecimentos", "empresas" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "hs_relatorio.marcacao_id" ).isEqual( new Field( "marcacoes_estabelecimento.id" ) ), - new Field( "marcacoes_estabelecimento.estabelecimento_id" ).isEqual( new Field( "estabelecimentos.id" ) ), - new Field( "estabelecimentos.empresa_id" ).isEqual( new Field( "empresas.id" ) ) - }, - new String[]{ "imprimir_tabela_alargada" }, - new Field( "hs_relatorio.id" ).isEqual( planoId ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - - return ( ( Boolean ) array.get( 0, 0 ) ).booleanValue(); - } - catch( Exception ex ) - { - return true; - } - } - - - public RelatorioToPrint getRelatorioToPrint( Integer id ) - throws Exception - { - Virtual2DArray array; - - Select select = new Select2( - new String[]{ "hs_relatorio", "marcacoes_estabelecimento", "estabelecimentos", "empresas" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "hs_relatorio.marcacao_id" ).isEqual( new Field( "marcacoes_estabelecimento.id" ) ), - new Field( "marcacoes_estabelecimento.estabelecimento_id" ).isEqual( new Field( "estabelecimentos.id" ) ), - new Field( "estabelecimentos.empresa_id" ).isEqual( new Field( "empresas.id" ) ) - }, - new String[]{ - "empresas.id", "empresas.designacao_social", "empresas.actividade", - "estabelecimentos.id", "estabelecimentos.nome", - "hs_relatorio.data", "marcacoes_estabelecimento.data", - "hs_relatorio.acompanhante1", "hs_relatorio.funcao_acompanhante1", - "hs_relatorio.acompanhante2", "hs_relatorio.funcao_acompanhante2", - "hs_relatorio.funcionarios", "estabelecimentos.morada", - "hs_relatorio.avaliacao_inicial"}, - new Field( "hs_relatorio.id" ).isEqual( id ), - null, - null, - null, - null - ); -// System.out.println( "\ngetRelatorioToPrint() : " + select.toString() ); - - array = EXECUTER.executeQuery( select ); - Integer empresaId = ( Integer ) array.get( 0, 0 ); - String nomeEmpresa = ( String ) array.get( 0, 1 ); - String actividadeEmpresa = ( String ) array.get( 0, 2 ); - Integer estabelecimentoId = ( Integer ) array.get( 0, 3 ); - String nomeEstabelecimento = ( String ) array.get( 0, 4 ); - Integer logoId = getLogotipoIdForEmpresaId( empresaId ); - Date dataRelatorio = ( Date ) array.get( 0, 5 ); - Date dataVisita = ( Date ) array.get( 0, 6 ); - Date dataProximaVisita = getDataProximaVisita( estabelecimentoId, dataVisita ); - String nomeAcompanhante = ( String ) array.get( 0, 7 ); - String funcaoAcompanhante = ( String ) array.get( 0, 8 ); - String nomeAcompanhante2 = ( String ) array.get( 0, 9 ); - String funcaoAcompanhante2 = ( String ) array.get( 0, 10 ); - String textoFuncionarios = ( String ) array.get( 0, 11 ); - String morada = ( String ) array.get( 0, 12 ); - String tipoAvaliacao = ( array.get( 0, 13 ) != null && ( ( Boolean ) array.get( 0, 13 ) ).booleanValue() ) ? "INICIAL" : "PERI\u00d3DICA"; - EmpresaToPrint empresa = new EmpresaToPrint( nomeEmpresa, - "http://www.evolute.pt:13080/SIPRPImages/image?id=" + logoId, - nomeEstabelecimento, actividadeEmpresa, - nomeAcompanhante, funcaoAcompanhante, nomeAcompanhante2, funcaoAcompanhante2, morada ); - RelatorioToPrint plano = new RelatorioToPrint( - empresa, - dataRelatorio != null ? new DataToPrint( "data-relatorio", dataRelatorio ) : null, - dataVisita != null ? new DataToPrint( "data-hs", dataVisita ) : null, - tipoAvaliacao, - dataProximaVisita != null ? new DataToPrint( "data-proxima-hs", dataProximaVisita ) : null, - textoFuncionarios, - getTecnicoHS( id ), - getTecnicoSuperiorHS( id ), - getLegislacaoAplicavel( id ), - getNormalizacaoAplicavel( id ), - getEquipamento( id ), - getAreasToPrint( id ) - ); - return plano; - } - - public Date getDataProximaVisita( Integer estabelecimentoId, Date dataVisita ) - throws Exception - { - Select select = - new Select2( - new String[]{ "marcacoes_estabelecimento" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "MIN( marcacoes_estabelecimento.data )" }, - new Field( "marcacoes_estabelecimento.estabelecimento_id" ).isEqual( estabelecimentoId ).and( - new Field( "marcacoes_estabelecimento.data" ).isGreater( dataVisita ) ).and( - new Field( "marcacoes_estabelecimento.estado" ).isEqual( 0 ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - if( array.columnLength() == 0 ) - { - return null; - } - else - { - return ( Date ) array.get( 0, 0 ); - } - } - - public Integer getLogotipoIdForEmpresaId( Integer empresaId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "empresas" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "empresa_logo_id" }, - new Field( "id" ).isEqual( empresaId ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - return array.columnLength() > 0 ? ( Integer ) array.get( 0, 0 ) : null; - } - - public TecnicoHSToPrint getTecnicoHS( Integer relatorioId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "hs_relatorio", "marcacoes_estabelecimento", "marcacoes_tecnicos_hst" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "hs_relatorio.marcacao_id" ).isEqual( new Field( "marcacoes_estabelecimento.id" ) ), - new Field( "marcacoes_estabelecimento.tecnico_hst" ).isEqual( new Field( "marcacoes_tecnicos_hst.id" ) ), - }, - new String[]{ - "marcacoes_tecnicos_hst.id", - "marcacoes_tecnicos_hst.nome", - "marcacoes_tecnicos_hst.cap", - "marcacoes_tecnicos_hst.formacao", - "marcacoes_tecnicos_hst.assinatura",}, - new Field( "hs_relatorio.id" ).isEqual( relatorioId ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - if( array.columnLength() == 0 ) - { - return null; - } - else - { - Integer id = ( Integer ) array.get( 0, 0 ); - String nome = ( String ) array.get( 0, 1 ); - String cap = ( String ) array.get( 0, 2 ); - String formacao = ( String ) array.get( 0, 3 ); - Integer assinatura = ( Integer ) array.get( 0, 4 ); - return new TecnicoHSToPrint( id, nome, cap, formacao, "http://www.evolute.pt:13080/SIPRPImages/image?id=" + assinatura, false ); - } - } - - public TecnicoHSToPrint getTecnicoSuperiorHS( Integer relatorioId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "hs_relatorio", "marcacoes_estabelecimento", "marcacoes_tecnicos_hst" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "hs_relatorio.marcacao_id" ).isEqual( new Field( "marcacoes_estabelecimento.id" ) ), - new Field( "marcacoes_estabelecimento.tecnico_superior_hst" ).isEqual( new Field( "marcacoes_tecnicos_hst.id" ) ), - }, - new String[]{ - "marcacoes_tecnicos_hst.id", - "marcacoes_tecnicos_hst.nome", - "marcacoes_tecnicos_hst.cap", - "marcacoes_tecnicos_hst.formacao", - "marcacoes_tecnicos_hst.assinatura",}, - new Field( "hs_relatorio.id" ).isEqual( relatorioId ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - if( array.columnLength() == 0 ) - { - return null; - } - else - { - Integer id = ( Integer ) array.get( 0, 0 ); - String nome = ( String ) array.get( 0, 1 ); - String cap = ( String ) array.get( 0, 2 ); - String formacao = ( String ) array.get( 0, 3 ); - Integer assinatura = ( Integer ) array.get( 0, 4 ); - return new TecnicoHSToPrint( id, nome, cap, formacao, "http://www.evolute.pt:13080/SIPRPImages/image?id=" + assinatura, true ); - } - } - - public LegislacaoAplicavelToPrint getLegislacaoAplicavel( Integer relatorioId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "hs_relatorio_legislacao" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "hs_relatorio_legislacao.categoria", "hs_relatorio_legislacao.descricao", - "COALESCE(hs_relatorio_legislacao.categoria,'A')"}, - new Field( "hs_relatorio_legislacao.hs_relatorio_id" ).isEqual( relatorioId ), - new String[]{ "COALESCE(hs_relatorio_legislacao.categoria,'A')", "ordem" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Vector diplomasGerais = new Vector(); - Vector nomes = new Vector(); - Vector> diplomas = new Vector>(); - String last = null; - for( int n = 0; n < array.columnLength(); n++ ) - { - String categoria = ( String ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - if( categoria == null || categoria.trim().length() == 0 ) - { - diplomasGerais.add( descricao ); - } - else - { - if( !categoria.equals( last ) ) - { - nomes.add( categoria ); - diplomas.add( new Vector() ); - } - last = categoria; - diplomas.lastElement().add( descricao ); - } - } - LegislacaoAplicavelToPrint legislacao = - new LegislacaoAplicavelToPrint( diplomasGerais, nomes.toArray( new String[ nomes.size() ] ), - diplomas.toArray( new Vector[ diplomas.size() ] )); - return legislacao; - } - - public NormalizacaoToPrint getNormalizacaoAplicavel( Integer relatorioId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "hs_relatorio_normalizacao" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "hs_relatorio_normalizacao.portuguesa", "hs_relatorio_normalizacao.descricao" }, - new Field( "hs_relatorio_normalizacao.hs_relatorio_id" ).isEqual( relatorioId ), - new String[]{ "hs_relatorio_normalizacao.portuguesa", "hs_relatorio_normalizacao.descricao" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Vector portuguesas = new Vector(); - Vector internacionais = new Vector(); - for( int n = 0; n < array.columnLength(); n++ ) - { - Boolean portuguesa = ( Boolean ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - if( portuguesa ) - { - portuguesas.add( descricao ); - } - else - { - internacionais.add( descricao ); - } - } - return new NormalizacaoToPrint( portuguesas, internacionais ); - } - - public EquipamentosToPrint getEquipamento( Integer relatorioId ) - throws Exception - { - Select select = - new Select2( - new String[]{ "hs_relatorio_equipamento" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "hs_relatorio_equipamento.tipo", "hs_relatorio_equipamento.marca", - "hs_relatorio_equipamento.modelo" }, - new Field( "hs_relatorio_equipamento.hs_relatorio_id" ).isEqual( relatorioId ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - EquipamentoToPrint equipamentos[] = new EquipamentoToPrint[ array.columnLength() ]; - for( int n = 0; n < array.columnLength(); n++ ) - { - String tipo = ( String ) array.get( n, 0 ); - String marca = ( String ) array.get( n, 1 ); - String modelo = ( String ) array.get( n, 2 ); - equipamentos[ n ] = new EquipamentoToPrint( tipo, marca, modelo ); - } - return new EquipamentosToPrint( equipamentos ); - } - - public Vector getAreasToPrint( Integer relatorioId ) - throws Exception - { - Virtual2DArray array; - Vector areas = new Vector(); - - Select select = new Select2( - new String[]{ "hs_relatorio_area" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "id", "description", "ordem" }, - new Field( "relatorio_id" ).isEqual( relatorioId ).and( - new Field( "deleted_date" ).isEqual( null ) ), - new String[]{ "id" }, - null, - null, - null - ); -// System.out.println( "\ngetAreasToPrint( " + relatorioId + " ) : " + select.toString() ); - array = EXECUTER.executeQuery( select ); - - for( int n = 0; n < array.columnLength(); n++ ) - { - Integer areaId = ( Integer ) array.get( n, 0 ); - String areaDescricao = ( String ) array.get( n, 1 ); - -// System.out.println( "\n\t\tAREA : " + areaDescricao ); - - Integer ordem = ( Integer ) array.get( n, 2 ); - Vector postos = getPostosToPrintByAreaId( areaId ); - if( postos.size() > 0 ) - { - boolean generico = false; - for( PostoToPrint posto : postos ) - { - generico |= posto.isGenerico(); - } - areas.add( new AreaToPrint( areaDescricao, postos, ordem, generico ) ); - } - } - Collections.sort( areas ); - return areas; - } - - public Vector getPostosToPrintByAreaId( Integer areaId ) - throws Exception - { - Vector postos = new Vector(); - Virtual2DArray array; - Select select = new Select2( - new String[]{ "hs_relatorio_posto" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ - "hs_relatorio_posto.id", "hs_relatorio_posto.description", "coalesce(hs_relatorio_posto.is_principal,'FALSE')" - }, - new Field( "hs_relatorio_posto.area_id" ).isEqual( areaId ).and( - new Field( "hs_relatorio_posto.deleted_date" ).isEqual( null ) - ), - new String[]{ "coalesce(hs_relatorio_posto.is_principal,'FALSE') DESC", "hs_relatorio_posto.id" }, - null, - null, - null - ); -// System.out.println( "\n\tgetPostosToPrintByAreaId( " + areaId + " ) : " + select.toString() ); - - array = EXECUTER.executeQuery( select ); - for( int n = 0; n < array.columnLength(); n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - -// System.out.println( "\n\t\t\tPOSTO : " + descricao ); - - Boolean generico = ( Boolean ) array.get( n, 2 ); - postos.add( new PostoToPrint( descricao, getRiscosToPrintByPostoId( id ), generico ) ); - } - return postos; - } - - public Vector getRiscosToPrintByPostoId( Integer postoId ) - throws Exception - { - Virtual2DArray array; - Vector riscos = new Vector(); - Select select = new Select2( - new String[]{ "hs_relatorio_risco", "hs_relatorio_posto_risco", "hs_relatorio_risco_valor_qualitativo" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_LEFT_OUTER }, - new Expression[]{ - new Field( "hs_relatorio_risco.id" ).isEqual( new Field( "hs_relatorio_posto_risco.risco_id" ) ), - new Field( "hs_relatorio_posto_risco.valor_qualitativo_id" ).isEqual( new Field( "hs_relatorio_risco_valor_qualitativo.id" ) ) - }, - new String[]{ - "hs_relatorio_risco.id", "hs_relatorio_risco.description", "hs_relatorio_posto_risco.probabilidade", - "hs_relatorio_posto_risco.severidade", "hs_relatorio_risco_valor_qualitativo.description" - }, - new Field( "hs_relatorio_posto_risco.posto_id" ).isEqual( postoId ).and( - new Field( "hs_relatorio_risco.deleted_date" ).isEqual( null ).and( - new Field( "hs_relatorio_posto_risco.probabilidade" ).isDifferent( null ).or( - new Field( "hs_relatorio_posto_risco.severidade" ).isDifferent( null ).or( - new Field( "hs_relatorio_posto_risco.valor_qualitativo_id" ).isDifferent( null ) - ) - ) - ) - ), - new String[]{ "hs_relatorio_posto_risco.probabilidade*hs_relatorio_posto_risco.severidade DESC" }, - null, - null, - null - ); -// System.out.println( "\n\t\tgetRiscosToPrintByPostoId( " + postoId + " ) : " + select.toString() ); - - array = EXECUTER.executeQuery( select ); - Vector riscosVector = new Vector(); - HashMap> riscosIdMap = new HashMap>(); - for( int n = 0; n < array.columnLength(); n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - -// System.out.println( "\n\t\t\t\tRISCO : " + descricao ); - - Integer probabilidade = ( Integer ) array.get( n, 2 ); - Integer severidade = ( Integer ) array.get( n, 3 ); - String valorQualitativo = ( String ) array.get( n, 4 ); - riscos.add( - new RiscoToPrint( - descricao, - severidade, - probabilidade, - valorQualitativo, - getMedidasToPrintByRiscoId( id ) ) ); - } - - Collections.sort(riscos, new Comparator(){ - - @Override - public int compare(RiscoToPrint o1, RiscoToPrint o2) { - Integer o1Value = 1000; - Integer o2Value = 1000; - if( o1.probabilidade != null && o1.severidade != null ) - { - o1Value = -o1.probabilidade*o1.severidade; - } - else if(o1.valorQualitativo.equals(UNCONTROLLED)) - { - o1Value = 100; - } - else if(o1.valorQualitativo.equals(CONTROLLED)) - { - o1Value = 200; - } - else if(o1.valorQualitativo.equals(INDETERMINATE)) - { - o1Value = 300; - } - else if ( o1.valorQualitativo.equals( NAO_VALORAVEL ) ) - { - o1Value = 400; - } - - if( o2.probabilidade != null && o2.severidade != null ) - { - o2Value = -o2.probabilidade*o2.severidade; - } - else if(o2.valorQualitativo.equals(UNCONTROLLED)) - { - o2Value = 100; - } - else if(o2.valorQualitativo.equals(CONTROLLED)) - { - o2Value = 200; - } - else if(o2.valorQualitativo.equals(INDETERMINATE)) - { - o2Value = 300; - } - else if ( o2.valorQualitativo.equals( NAO_VALORAVEL ) ) - { - o2Value = 400; - } - - if( o1Value == -4 && o2Value == -4 ) - { - o1Value = o1.probabilidade + o1.severidade; - o2Value = o2.probabilidade + o2.severidade; - } - return o1Value.compareTo( o2Value ); - } - }); - - return riscos; - } - - public Vector getMedidasToPrintByRiscoId( Integer riscoId ) - throws Exception - { - Vector medidas = new Vector(); - Select select = new Select2( - new String[]{ "hs_relatorio_medida" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ - "hs_relatorio_medida.id", "hs_relatorio_medida.requesitos_legais", "hs_relatorio_medida.description" - }, - new Field( "hs_relatorio_medida.risco_id" ).isEqual( riscoId ).and( - new Field( "hs_relatorio_medida.deleted_date" ).isEqual( null ) - ), - new String[]{ "hs_relatorio_medida.id" }, - null, - null, - null - ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - for( int n = 0; n < array.columnLength(); n++ ) - { - String requisitosLegais = ( String ) array.get( n, 1 ); - String descricao = ( String ) array.get( n, 2 ); - medidas.add( new MedidaToPrint( requisitosLegais, descricao ) ); - } - return medidas; - } - - /** - * Para fazer dump dos logotipos para converter para jpeg - */ - public Mappable[] getLogotipos() - throws Exception - { - Select select = - new Select2( - new String[]{ "image" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "id", "image_data" }, - null, - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Mappable logotipos[] = new Mappable[ array.columnLength() ]; - for( int n = 0; n < logotipos.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - byte data[] = ( byte[] ) array.get( n, 1 ); - logotipos[ n ] = - new MappableObject( id, data ); - } - return logotipos; - } - - /** - * Para fazer import dos logotipos convertidos para jpeg - */ - public void updateLogotipo( Integer id, byte[] data ) - throws Exception - { - BlobUpdate update = - new BlobUpdate( "image", "image_data", data, new Field( "id" ).isEqual( id ) ); - EXECUTER.executeQuery( update ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioToPrint.java deleted file mode 100644 index 0c36facb..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RelatorioToPrint.java +++ /dev/null @@ -1,96 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - -public class RelatorioToPrint - implements PrintableInterface -{ - protected EmpresaToPrint empresa; - protected DataToPrint dataRelatorio; - protected DataToPrint dataHs; - protected String tipoAvaliacao; - protected DataToPrint dataProximaHs; - protected String textoFuncionarios; - protected TecnicoHSToPrint tecnicoHS; - protected TecnicoHSToPrint tecnicoSuperiorHS; - protected LegislacaoAplicavelToPrint legislacaoAplicavel; - protected NormalizacaoToPrint normalizacaoAplicavel; - protected EquipamentosToPrint equipamentos; - protected Vector areas; - - public RelatorioToPrint( EmpresaToPrint empresa, - DataToPrint dataRelatorio, - DataToPrint dataHs, - String tipoAvaliacao, - DataToPrint dataProximaHs, - String textoFuncionarios, - TecnicoHSToPrint tecnicoHS, - TecnicoHSToPrint tecnicoSuperiorHS, - LegislacaoAplicavelToPrint legislacaoAplicavel, - NormalizacaoToPrint normalizacaoAplicavel, - EquipamentosToPrint equipamentos, - Vector areas ) - { - super(); - this.empresa = empresa; - this.dataRelatorio = dataRelatorio; - this.dataHs = dataHs; - this.tipoAvaliacao = tipoAvaliacao; - this.dataProximaHs = dataProximaHs; - this.textoFuncionarios = textoFuncionarios; - this.tecnicoHS = tecnicoHS; - this.tecnicoSuperiorHS = tecnicoSuperiorHS; - this.legislacaoAplicavel = legislacaoAplicavel; - this.normalizacaoAplicavel = normalizacaoAplicavel; - this.equipamentos = equipamentos; - this.areas = areas; - } - - @Override - public Element toJdomElement() throws Exception - { - Element relatorioElement = new Element( "relatorio" ); - relatorioElement.addContent( empresa.toJdomElement() ); - relatorioElement.addContent( dataRelatorio.toJdomElement() ); - relatorioElement.addContent( dataHs.toJdomElement() ); - Element tipoAvaliacaoElement = new Element( "tipo-avaliacao" ); - tipoAvaliacaoElement.setText( tipoAvaliacao ); - relatorioElement.addContent( tipoAvaliacaoElement ); - Element tipoAvaliacaoCamelElement = new Element( "tipo-avaliacao-camel" ); - tipoAvaliacaoCamelElement.setText( tipoAvaliacao.charAt(0) + tipoAvaliacao.toLowerCase().substring(1) ); - relatorioElement.addContent( tipoAvaliacaoCamelElement ); - if( dataProximaHs != null ) - { - relatorioElement.addContent( dataProximaHs.toJdomElement() ); - } - if( textoFuncionarios != null ) - { - Element textoFuncionariosElement = new Element( "texto-funcionarios" ); - textoFuncionariosElement.setText( textoFuncionarios ); - relatorioElement.addContent( textoFuncionariosElement ); - } - if( tecnicoHS != null ) - { - relatorioElement.addContent( tecnicoHS.toJdomElement() ); - } - if( tecnicoSuperiorHS != null ) - { - relatorioElement.addContent( tecnicoSuperiorHS.toJdomElement() ); - } - relatorioElement.addContent( legislacaoAplicavel.toJdomElement() ); - relatorioElement.addContent( normalizacaoAplicavel.toJdomElement() ); - relatorioElement.addContent( equipamentos.toJdomElement() ); - if( areas.size() > 0 ) - { - Element conclusoesElement = new Element( "conclusoes" ); - for( AreaToPrint area : areas ) - { - conclusoesElement.addContent( area.toJdomElement() ); - } - relatorioElement.addContent( conclusoesElement ); - } - return relatorioElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RiscoToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RiscoToPrint.java deleted file mode 100644 index f558f0eb..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/RiscoToPrint.java +++ /dev/null @@ -1,59 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.util.Vector; - -import org.jdom.Element; - -public class RiscoToPrint - implements PrintableInterface -{ - protected String descricao; - protected Integer severidade; - protected Integer probabilidade; - protected String valorQualitativo; - protected Vector medidas; - - public RiscoToPrint( String descricao, Integer severidade, Integer probabilidade, - String valorQualitativo, Vector medidas ) - { - super(); - this.descricao = descricao; - this.severidade = severidade; - this.probabilidade = probabilidade; - this.valorQualitativo = valorQualitativo; - this.medidas = medidas; - } - - @Override - public Element toJdomElement() throws Exception - { - Element riscoElement = new Element( "risco" ); - Element descricaoElement = new Element( "descricao" ); - descricaoElement.setText( descricao ); - riscoElement.addContent( descricaoElement ); - if( severidade != null ) - { - Element severidadeElement = new Element( "severidade" ); - severidadeElement.setText( severidade != null ? severidade.toString() : " " ); - riscoElement.addContent( severidadeElement ); - } - if( probabilidade != null ) - { - Element probabilidadeElement = new Element( "probabilidade" ); - probabilidadeElement.setText( probabilidade != null ? probabilidade.toString() : " " ); - riscoElement.addContent( probabilidadeElement ); - } - Element valorElement = new Element( "valor-numerico" ); - valorElement.setText( ( severidade != null && probabilidade != null ) ? "" + ( severidade * probabilidade ) : " " ); - riscoElement.addContent( valorElement ); - Element valorQualitativoElement = new Element( "valor-qualitativo" ); - valorQualitativoElement.setText( valorQualitativo != null ? valorQualitativo : " " ); - riscoElement.addContent( valorQualitativoElement ); - for( MedidaToPrint medida : medidas ) - { - riscoElement.addContent( medida.toJdomElement() ); - } - - return riscoElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TecnicoHSToPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TecnicoHSToPrint.java deleted file mode 100644 index 88fe4715..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TecnicoHSToPrint.java +++ /dev/null @@ -1,45 +0,0 @@ -package siprp.higiene.relatorio.print; - -import org.jdom.Element; - -public class TecnicoHSToPrint - implements PrintableInterface -{ - protected Integer id; - protected String nome; - protected String cap; - protected String formacao; - protected String assinatura; - protected boolean superior; - - public TecnicoHSToPrint( Integer id, String nome, String cap, - String formacao, String assinatura, boolean superior ) - { - super(); - this.id = id; - this.nome = nome; - this.cap = cap; - this.formacao = formacao; - this.assinatura = assinatura; - this.superior = superior; - } - - @Override - public Element toJdomElement() throws Exception - { - Element tecnicoHSElement = new Element( "tecnico" + ( superior ? "-superior" : "" ) + "-hs" ); - Element nomeElement = new Element( "nome" ); - nomeElement.setText( nome ); - tecnicoHSElement.addContent( nomeElement ); - Element capElement = new Element( "cap" ); - capElement.setText( cap ); - tecnicoHSElement.addContent( capElement ); - Element formacaoElement = new Element( "formacao" ); - formacaoElement.setText( formacao ); - tecnicoHSElement.addContent( formacaoElement ); - Element assinaturaElement = new Element( "assinatura" ); - assinaturaElement.setText( "" + assinatura ); - tecnicoHSElement.addContent( assinaturaElement ); - return tecnicoHSElement; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TestPrint.java b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TestPrint.java deleted file mode 100644 index a72201e8..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/TestPrint.java +++ /dev/null @@ -1,87 +0,0 @@ -package siprp.higiene.relatorio.print; - -import java.io.ByteArrayOutputStream; -import java.io.FileOutputStream; -import java.io.InputStream; - -import shst.util.fop.PDFCreator; - -import com.evolute.utils.xml.XSLTransformer; - -public class TestPrint -{ - public static void main( String args[] ) - throws Exception - { - new TestPrint().test(); - } - - public void test() - throws Exception - { -// FileOutputStream fos; -// -//// PlanoActuacaoDBInit.initDB(); -//// PlanoActuacaoToPrint plano = PlanoActuacaoPrintDataProvider.getProvider().getPlanoToPrint( 6 ); -// Element evoluteElement = new Element( "evolute" ); -// Document foDoc = new Document( evoluteElement ); -// Format pretty = Format.getPrettyFormat(); -// pretty.setIndent("\t"); -// XMLOutputter outputter = new XMLOutputter(pretty); -// ByteArrayOutputStream foBaos = new ByteArrayOutputStream(); -// outputter.output( foDoc, foBaos ); -//// FileOutputStream fos = new FileOutputStream( "/home/fpalma/Desktop/in.xml" ); -//// fos.write( foBaos.toByteArray() ); -//// fos.close(); -// -// byte fo[] = applyTemplate( -//// "siprp/planoactuacao/print/plano_actuacao.xsl", -//// getClass().getClassLoader().getResourceAsStream( "siprp/higiene/relatorio/relatorio.xsl" ), -// new FileInputStream( "/home/fpalma/projectos2/SIPRP/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio.xsl" ), -//// "siprp/planoactuacao/print/teste_input.xml" ); -// new FileInputStream( "/home/fpalma/projectos2/SIPRP/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input.xml" ) ); -//// new ByteArrayInputStream( foBaos.toByteArray() ) ); -//// new ByteArrayInputStream( "".getBytes() ) ); -//// System.out.println( new String( fo ) ); -// System.out.println( new String(fo) ); -// createPDFFile( fo, "/home/fpalma/Desktop/out.pdf" ); -//// createPDFFile( fo, "c:/Documents and Settings/Frederico/Ambiente de Trabalho/out.pdf" ); -// -// fos = new FileOutputStream( "/home/fpalma/Desktop/out.xml" ); -// fos.write( fo ); -// fos.close(); - - for( int n = 59; n <= 59; n++ ) - { - byte pdf[] = new RelatorioPDFCreator().createPDF( n ); - FileOutputStream fos = new FileOutputStream( "/home/fpalma/Desktop/" + n + ".pdf" ); - fos.write( pdf ); - fos.close(); - } - } - - public void createPDFFile( byte fo[], String path ) - throws Exception - { - byte pdf[] = PDFCreator.getPDFCreator().createPdfFromFo( fo ); - FileOutputStream fos = new FileOutputStream( path ); - fos.write( pdf ); - fos.close(); - } - - public byte[] applyTemplate( String template, String data ) - throws Exception - { - InputStream xsl = getClass().getClassLoader().getResourceAsStream( template ); - InputStream xml = getClass().getClassLoader().getResourceAsStream( data ); - return( applyTemplate( xsl, xml ) ); - } - - public byte[] applyTemplate( InputStream xsl, InputStream dataStream ) - throws Exception - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - XSLTransformer.getXSLTransformer().transform( dataStream, xsl, baos ); - return baos.toByteArray(); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio.xsl b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio.xsl deleted file mode 100644 index d6cdad71..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio.xsl +++ /dev/null @@ -1,2874 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ATRIUM SALDANHA   - - - Praça Duque de Saldanha, 1 – 9º G   - - - 1050 – 094 Lisboa   - - - Telefone (+351) 213 504 540   - - - Fax (+351) 213 504 549   - - - geral@siprp.pt   - - - www.siprp.com   - - - - - - - Lisboa   - - - - - de - - - - - - - - - - - - AVALIAÇÃO DOS RISCOS PROFISSIONAIS   - - - Relatório - - -   - - -   - - -   - - - - - - - - - -   - - -   - - - - - - - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - - - - - - - ÍNDICE - - - - - - - - - - - - 1. INTRODUÇÃO - - - - - - - 2. AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - 3. MEDIÇÃO DOS FACTORES DE RISCO - - - - - - - 4. LEGISLAÇÃO APLICÁVEL - - - - - - - 4.1 Legislação de aplicação geral - - - - - - - 4.2 Legislação específica - - - - - - - 5. NORMALIZAÇÃO APLICÁVEL - - - - - - - 6. EMPRESA CLIENTE - - - - - - - 7. TABELAS DE AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - 8. PLANO DE ACTUAÇÃO - - - - - - - 9. ACOMPANHAMENTO - - - - - - - 10. CONSIDERAÇÕES FINAIS - - - - - -   - - -   - - - - - - - - 1 - INTRODUÇÃO   - - - - - - - - - - - O empregador deve assegurar aos trabalhadores condições de segurança e saúde em todos os aspectos relacionados com o trabalho, aplicando as medidas necessárias tendo em conta os princípios gerais de prevenção. - - - - - Na aplicação das medidas de prevenção, o empregador deve mobilizar os meios necessários, nomeadamente nos domínios da prevenção técnica, da formação, informação e consulta dos trabalhadores e de serviços adequados, internos ou externos à empresa. - - - - - De acordo com a Lei nº 102/2009 de 10 de Setembro, que regulamenta o regime jurídico da promoção e prevenção da segurança e da saúde no trabalho, a prevenção dos riscos profissionais deve assentar numa correcta e permanente avaliação de riscos. - - - - - Enquanto entidade prestadora de serviços externos, a SIPRP - Sociedade Ibérica de Prevenção de Riscos Profissionais fomenta a implementação das medidas necessárias para prevenir os riscos profissionais e promover a segurança e a saúde dos trabalhadores, nomeadamente através da planificação da prevenção (integrando a todos os níveis a avaliação dos riscos e respectivas medidas de prevenção), da avaliação de riscos (com elaboração do respectivo relatório), da elaboração do plano de prevenção dos riscos profissionais e dos planos detalhados de prevenção e protecção (planos de actuação). - - - - - O presente documento reflecte a avaliação dos riscos profissionais realizada, assim como as medidas de prevenção tidas como necessárias. - - - - - Será igualmente emitido um outro documento no qual se elabora o plano de prevenção dos riscos profissionais, o qual é denominado de Plano de Actuação. - - - - - - - - - - - - - - 2 - AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - - - - - Uma avaliação de riscos profissionais é um exame cuidadoso, realizado nos locais de trabalho, que tem como objectivo detectar os componentes aí existentes capazes de causar dano(s) ao(s) trabalhador(es) expostos. Na prática, trata-se de um processo dinâmico que reúne um duplo objectivo: - - - - - - - - - - • - - - - - Estimar a gravidade que um determinado risco no trabalho pode ter para a saúde e segurança dos trabalhadores, resultante das circunstâncias em que o perigo pode ocorrer; - - - - - - - • - - - - - Obter a informação necessária para que o empregador reúna condições para uma tomada de decisão apropriada, nomeadamente informação sobre a necessidade e o tipo de medidas preventivas a adoptar. - - - - - - - - A avaliação de riscos profissionais constitui um processo dinâmico, uma vez que os riscos profissionais que a entidade patronal se vê obrigada a avaliar não ficam definitivamente determinados, mas vão evoluindo à medida que alterações se vão efectuando em função: - - - - - - - - - - • - - - - - do desenvolvimento progressivo das condições de trabalho; - - - - - - - - - - - • - - - - - das investigações científicas em matéria de riscos profissionais. - - - - - - - - A avaliação dos riscos profissionais deve ser eficiente e suficientemente detalhada para possibilitar uma adequada hierarquização dos riscos e consequente controlo. - - - - - Uma vez que assume uma linguagem mais objectiva, a SIPRP optou pelo método de matriz simples 4x4, que envolve a quantificação da probabilidade e da gravidade. - - - - - O método referido recorre a duas escalas de quatro níveis, para quantificar as variáveis gravidade e probabilidade. - - - - - - - - - - - - Gravidade - - - - - - - - Probabilidade  - - - - - - - - Improvável   - - - 1   - - - - - Ocasional   - - - 2   - - - - - Provável   - - - 3   - - - - - Frequente   - - - 4   - - - - - - - Negligenciável - - - 1   - - - - - Aceitável   - - - 1   - - - - - Médio - - - 2   - - - - - Médio - - - 3   - - - - - Alto - - - 4   - - - - - - - Marginal - - - 2   - - - - - Médio - - - 2   - - - - - Médio   - - - 4   - - - - - Alto   - - - 6   - - - - - Muito alto   - - - 8   - - - - - - - Crítico - - - 3   - - - - - Médio - - - 3   - - - - - Alto   - - - 6   - - - - - Muito alto   - - - 9   - - - - - Extremamente alto - - - 12   - - - - - - - Catastrófico - - - 4   - - - - - Alto   - - - 4   - - - - - Muito alto   - - - 8   - - - - - Extremamente alto - - - 12   - - - - - Extremamente alto - - - 16   - - - - - - - Quadro – Matriz simples 4x4 - - - - - A interpretação do valor obtido pode ser realizada através da consulta do índice de risco, que traduz a prioridade de intervenção associada à avaliação feita. - - - - - - - - - - - Indice de risco - - - - - prioridade de intervenção - - - - - - - Aceitável - - - - - Actuação não prioritária - - - - - - - Médio - - - - - Intervenção a médio prazo - - - - - - - Alto - - - - - Intervenção a curto prazo - - - - - - - Muito alto - - - - - Actuação urgente - - - - - - - Extremamente alto - - - - - Actuação imediata - - - - - - - Quadro – Prioridade de intervenção de acordo com o índice de risco - - - Alguns riscos profissionais poderão ainda ser classificados como - indeterminados, dada a insuficência de informação. - - - São identificados igualmente requisitos legais, de carácter obrigatório e a que se encontram associados factores de risco. São apresentados com uma classificação de não valorável. - - - - - - - - - - - - 3 - MEDIÇÃO DOS FACTORES DE RISCO - - - - - - - - - - - Uma vez que um dos princípios gerais de prevenção é assegurar que as exposições aos agentes químicos, físicos e biológicos e aos factores de risco psicossociais não constituem risco para a segurança e saúde do trabalhador nos locais de trabalho, a SIPRP, no decorrer das avaliações dos riscos profissionais, realiza medições aos seguintes parâmetros: - - - - - - - - - - • - - - - - Iluminância ou nível de iluminação; - - - - - - - • - - - - - Temperatura do ar; - - - - - - - • - - - - - Humidade relativa do ar; - - - - - - - • - - - - - Nível sonoro contínuo equivalente (ruído). - - - - - - - - Para realizar as referidas medições são utilizados os seguintes equipamentos: - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - Todos os equipamentos encontram-se devidamente calibrados por entidades acreditadas pelo Instituto Português de Acreditação. - - - - - - - - - - - - - - 4 - LEGISLAÇÃO APLICÁVEL - - - - - - - - - - - A avaliação dos riscos profissionais realizada pela SIPRP tem em conta as prescrições indicadas na legislação portuguesa em matéria de Segurança, Higiene e Saúde do Trabalho: - - - - - - - 4.1 Aplicação geral - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - 4.2 Aplicação específica - - - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - - - - - 5 - NORMALIZAÇÃO APLICÁVEL - - - - - - - - - - - Na realização da avaliação dos riscos profissionais é considerada além da legislação, também a normalização relativa à Segurança, Higiene e Saúde do Trabalho.  - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - - - - 6 - EMPRESA CLIENTE - - - - - - - - - - - A SIPRP realizou a avaliação dos riscos profissionais na empresa - , - estabelecimento de , - no dia - - de - - de - . - - - - - A actividade desenvolvida pela empresa é de . - - - - - De acordo com indicações fornecidas, . - - - - - No decorrer da avaliação dos riscos profissionais, - a SIPRP obteve a colaboração e acompanhamento de - - ( - - ) - - e - ( - - ) - . - - - - - - - - - - - - - - 7 - TABELAS DE AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - - - - - A avaliação dos riscos profissionais realizada encontra-se nas tabelas que são apresentadas seguidamente. Nas mesmas são referidas igualmente as respectivas medidas de prevenção tidas como necessárias. - - - - - Os riscos comuns a todos os postos de trabalho encontram-se agrupados por forma a facilitar a leitura do presente documento. - - - ÍNDICE DAS TABELAS DE RISCO POR ÁREA DE - ACTIVIDADE - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8 - PLANO DE ACTUAÇÃO - - - - - - - - - - - Após a avaliação dos riscos profissionais e da indicação das respectivas medidas de prevenção tidas como necessárias, a SIPRP emite um documento no qual é elaborado o plano de prevenção dos riscos profissionais, denominado de Plano de Actuação. - - - - - - - - - - - - - - 9 - ACOMPANHAMENTO - - - - - - - - - - - A SIPRP acompanha a execução das medidas de prevenção através de assessoramento ao cliente durante o preenchimento do Plano de Actuação. -   - - - - - A execução das medidas de prevenção são verificadas através da realização da avaliação dos riscos profissionais periódica. -   - - - - - - - - - - - - - - 10 - CONSIDERAÇÕES FINAIS - - - - - - - - - - - A SIPRP agradece a disponibilidade e o apoio de todos os colaboradores da empresa e fica ao dispor para qualquer esclarecimento. - - - - - - - - - Lisboa, - - de - - de - - - -   - - -  Realizado por: - - - - - - - - - - - - - - - - - - -   - - - - - - Técnico de Higiene e Segurança -   - - - CAP nº - - - - - - - - - - - -  Verificado por: - - - - - - - - - - - - - - - - - - -   - - - - - - Técnico Superior de Higiene e Segurança -   - - - CAP nº - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Avaliação de riscos profissionais   - - - - - - -   - - - - Empresa: - - - - - - - - - - -   - - - - Estabelecimento: - - - - - - - - - - - - Data da avaliação: - - - - de - - de - - -   - - - - - - Avaliação: - - - - -   - - - - - - Próxima avaliação: - - - - de - - de - - -   - - - - - - - - Realizada por: - - - - - - - - - - / SIPRP – - Sociedade Ibérica de Prevenção - de Riscos Profissionais   - - - - - - - - - Posto de trabalho: - - - - - - - - - - - - - - - - - - - Grav.   - - - (G)   - - - - - Prob.   - - - (P)   - - - - - Valor Risco   - - - (G x P)   - - - - - risco / requisito legal e medidas de prevenção - - - - - - - - - - - -   - - - - -   - - - - -   - - - - -   - - - - - - -   - - - - -   - - - - -   - - - - -   - - - - - - -   - - - - -   - - - - -   - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - Aceitável - - - Médio - - - Médio - - - - - Médio - - - Alto - - - - - Alto - - - Muito alto - - - Muito alto - - - Extremamente alto - - - Extremamente alto - - - - - - - - - - - -   - - - - -   - - - - - - - -   - - - - - - - - - - - - - - - - . - - - ; - - - - - - - -   - - - - - - - - . - - - ; - - - - -   - - - -   - - - - - - - - - - - - - - - - - - - - - - - - Avaliação - - - - - - - dos Riscos Profissionais - - - - - - - - - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_new.xsl b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_new.xsl deleted file mode 100644 index adc69ba1..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_new.xsl +++ /dev/null @@ -1,3671 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ATRIUM SALDANHA   - Praça Duque de Saldanha, 1 – 9º G   - 1050 – 094 Lisboa   - Telefone (+351) 213 504 540   - Fax (+351) 213 504 549   - geral@siprp.pt   - www.siprp.com   - - - Lisboa   - - - - de - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - Relatório -   -   -   -   -   -   -   - - - - -   -   - - - - - -   - -   - - - - - - -   -   -   - - - - - - Avaliação Periódica de Riscos Laborais -   -   - - - 113 - -   - - - -   -   - 9. PLANO DE ACTUAÇÃO   -   - A partir dos resultados da avaliação de riscos, - é elaborado um outro documento (Plano de - Actuação), que inclui a listagem das acções que - deverão ser realizadas de modo a eliminar, - reduzir ou controlar os riscos detectados.   - - Este Plano permitirá auxiliar a - AUCHAN - - - Loja de Coimbra - na programação e acompanhamento das - referidas acções. -   - -   -   - 10. CONSIDERAÇÕES FINAIS   -   - - A equipa técnica de Segurança e Higiene do - Trabalho da SIPRP agradece a colaboração de - todos os colaboradores da - AUCHAN - - - Loja de Coimbra - durante a realização desta auditoria, - ficando à disposição para qualquer - esclarecimento. -   - -   -   -   - Lisboa, 29 de Abril de 2008   -   - - - - - -   - Sónia Campos   - Ergonomista   - Téc. Sup. Seg. Hig. do Trabalho -   - (CAP nº 0601/6505/02)   - - - - -   -   -   -   - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old.xsl b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old.xsl deleted file mode 100644 index 6da1dd6e..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old.xsl +++ /dev/null @@ -1,3833 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - vbvb   - - - - -   - - - - - - - -   - - Avaliação Periódica de Riscos Laborais -   -   -   -   -   -   - - - -   -   - ÍNDICE   - - 1. INTRODUÇÃO - - - - - 2. DADOS DA EMPRESA - - - - - 3. LEGISLAÇÃO APLICÁVEL - - - - - 3.1 Legislação de aplicação geral - - - - - 3.2 Legislação específica - - - - - 4. NORMALIZAÇÃO APLICÁVEL - - - - - 4.1 Normalização portuguesa - - - - - 4.2 Normalização internacional - - - - - 5. OBRIGAÇÕES LEGAIS - - - - - 5.1 Obrigações do empregador - - - - - 5.2 Obrigações do trabalhador - - - - - 6. EQUIPAMENTOS UTILIZADOS - - - - - 7. RISCOS LABORAIS - - - - - 7.1 Classificação dos riscos profissionais - - - - - 7.2 Valoração dos riscos - - - - - 8. AVALIAÇÃO DE RISCOS LABORAIS - - - - - - - - -   -   -   - 1. INTRODUÇÃO   -   - A entidade empregadora deve tomar todas as - medidas necessárias para a defesa da segurança e - saúde dos seus trabalhadores, mediante a criação - de um sistema organizado, dotado dos meios - necessários, que deve abranger as medidas de - eliminação e de controlo dos riscos, assim como - de formação, informação e consulta a empreender. -   - - De acordo com a Lei nº 35/2004 de 29 de - Julho, que contém os princípios que visam - promover a segurança, higiene e saúde do - trabalho, o empregador deve “ - Integrar no conjunto de actividades da - empresa … a avaliação dos riscos para a - segurança e saúde dos trabalhadores, com a - adopção de convenientes medidas de - prevenção.” -   - - Tendo em vista assegurar condições adequadas de - segurança, higiene e saúde dos trabalhadores, - são realizadas auditorias de segurança, no - decorrer das quais:   - - 1 - é recolhida informação através das visitas - aos locais de trabalho, do diálogo - estabelecido com os trabalhadores ou através - de outras fontes de informação;   - - - 2 - é listado o conjunto de factores de risco - inerentes às condições normais de laboração - ou aos acontecimentos não planeados mas - previsíveis;   - - - 3 - são identificados os trabalhadores - potencialmente expostos a riscos resultantes - dos factores de risco identificados;   - - - 4 - é recolhida informação relativa à existência - de grupos específicos (jovens, grávidas, - puérperas, lactantes);   - - - 5 - são identificados os trabalhadores - envolvidos em trabalhos proibidos, - condicionados ou não recomendados;   - - - 6 - são identificadas as situações de perigo - grave ou iminente.   - - A avaliação dos riscos laborais consiste - portanto, na análise estruturada de todos os - aspectos inerentes ao trabalho, concretizada - através da identificação, estimação e valoração - dos riscos existentes (com indicação dos - trabalhadores a eles expostos) e da definição - das medidas de prevenção ou protecção adequadas. -   -   -   -   -   - 2. DADOS DA EMPRESA   -   - - No dia - 6 de Março 2008 - realizou-se a auditoria às instalações da - empresa - JUMBO – Loja integrada no C. C. - Dolce Vita - Coimbra - , situada na - R. D. João III, Coimbra - (cuja actividade desenvolvida é de comércio - a retalho em supermercados e hipermercados) - para a avaliação das condições de segurança, - higiene e saúde do trabalho existentes. -   - - A empresa supracitada possui duzentos e sessenta - e quatro (264) funcionários, sendo que setenta e - seis (76) destes exercem actividades na zona de - produtos frescos.   - Para a realização da visita, a Técnica Superior - de Segurança e Higiene do Trabalho da Sociedade - Ibérica de Prevenção de Riscos Profissionais - Unipessoal Lda., obteve a colaboração e - acompanhamento do Sr. Carlos Beijinho - (Responsável de Segurança) na prestação de - informações relativas à actividade desenvolvida - e às condições de trabalho existentes.   -   -   - 3. LEGISLAÇÃO APLICÁVEL   -   - A avaliação de riscos laborais realizada foi - baseada nas obrigações impostas pela legislação - portuguesa em vigor relativa à Segurança, - Higiene e Saúde do Trabalho.   -   - 3.1 Legislação de aplicação geral   - - - -   - Lei nº 99/2003 de 27 de Agosto regulamentada - pela Lei nº 35/2004 de 29 de Julho – Aprova o - novo Código de Trabalho;   - - - - - -   - Decreto-Lei n.º441/91 de 14 de Novembro, - - alterado pelo - Decreto-Lei n.º133/99 de 21 de Abril – - Estabelece o regime jurídico do - enquadramento da segurança, higiene e saúde - do trabalho; -   - - - - - -   - Decreto-Lei n.º26/94, de 1 de Fevereiro, - - alterado - pela Lei n.º7/95 de 29 de Março e pelo - Decreto-Lei n.º109/2000 – Regime de - Organização e funcionamento dos serviços da - segurança, higiene e saúde do trabalho; -   - - - - -   - Decreto-Lei n.º 347/93 de 1 de Outubro e - Portaria n.º987/93 de 6 de Outubro – Relativos - às prescrições mínimas de segurança nos locais - de trabalho.   - -   -   - 3.2 Legislação específica   - Acidentes de Trabalho e Doenças Profissionais   - - 1 - Lei nº100/97, de 13 de Setembro - regulamentado pelo Decreto-Lei n.º143/99 de - 30 de Abril – Aprova o novo regime jurídico - dos acidentes de trabalho e doenças - profissionais;   - - - 2 - Decreto-Lei nº 341/93 de 30 de Setembro – - Aprova a Tabela Nacional de Incapacidades de - Trabalho;   - - - 3 - Decreto Regulamentar nº 6/2001 de 5 de Maio - – Aprova a lista das doenças profissionais e - o respectivo índice codificado.   - - Grupos Específicos de Trabalhadores   - - 1 - Portaria nº 229/96 de de 26 de Junho – - Relativa à Protecção da segurança e da saúde - das trabalhadoras grávidas, puérperas e - lactantes.   - - Comércio e serviços   - - 1 - Decreto-Lei nº243/86 de 20 de Agosto – - Aprova o Regulamento Geral de Higiene e - Segurança de Trabalho nos Estabelecimentos - Comerciais, de Escritórios e Serviços;   - - Equipamentos de Protecção Individual   - - 1 - Decreto-Lei nº 348/93 de 1 de Outubro – - Relativo às prescrições mínimas de segurança - e de saúde para a utilização pelos - trabalhadores de equipamentos de protecção - individual no trabalho;   - - - 2 - Portaria nº 988/93 de 6 de Outubro – - Estabelece as prescrições mínimas de - segurança e saúde dos trabalhadores na - utilização de equipamentos de protecção - individual no trabalho.   - - Sinalização de segurança   - - 1 - Decreto-Lei n.º141/95, de 14 de Junho - regulamentado pela Portaria n.º1456-A/95, de - 11 de Dezembro – Estabelece as prescrições - mínimas para a sinalização de segurança e de - saúde no trabalho.   - - Segurança contra incêndios   - - 1 - - Decreto-Lei nº 368/99 de 18 de Setembro - – Aprova as medidas de segurança contra - riscos de incêndio aplicáveis aos - estabelecimentos comerciais com área - total igual ou superior a 300 m - 2 - . -   - - -   -   - Máquinas e equipamentos   - - 1 - Decreto-Lei nº 50/2005 de 25 de Fevereiro – - Relativo às prescrições mínimas de segurança - e de saúde para a utilização de equipamentos - de trabalho;   - - - 2 - Decreto-Lei nº 320/2001 de 12 de Dezembro – - Estabelece as regras a que deve obedecer a - colocação no mercado e a entrada em serviço - das máquinas e dos componentes de segurança - e colocados no mercado isoladamente.   - - Risco e instalações eléctricas   - - 1 - Portaria nº 37/70 de 21 de Janeiro – Aprova - as instruções para os primeiros socorros em - acidentes pessoais produzidos por correntes - eléctricas;   - - - 2 - - Portaria nº 949A/2006, de 11 de Setembro - – Relativo às Regras Técnicas das - Instalações Eléctricas - de Baixa Tensão; -   - - - Agentes biológicos   - - 1 - Decreto-lei nº 84/97 de 16 de Abril – - Estabelece prescrições mínimas de protecção - da segurança e da saúde dos trabalhadores - contra os riscos da exposição a agentes - biológicos durante o trabalho.   - - Agentes químicos   - - 1 - Decreto-lei nº 290/201 de 16 de Novembro – - Relativo à protecção da segurança e saúde - dos trabalhadores contra os riscos ligados à - exposição a agentes químicos no trabalho.   - - Desempenho energético dos edifícios   - - 1 - Decreto-Lei n.º 78/06 de 4 de Abril – - Relativo ao desempenho energético dos - edifícios;   - - - 2 - Decreto-Lei nº 79/2006 de 4 de Abril - - Aprova o regulamento dos Sistemas - Energéticos de Climatização em Edifícios.   - - Ruído   - - 1 - Decreto-lei nº 182/2006 de 6 de Setembro – - Relativo às prescrições mínimas de segurança - e saúde em matéria de exposição dos - trabalhadores aos riscos devidos ao ruído.   - -   -   - Classificação, embalagem e rotulagem   - - - -   - Portaria nº 732-A/96 de 11 de Dezembro – - Estabelecer as regras a que devem obedecer a - notificação de novas substâncias químicas e a - classificação, embalagem e rotulagem que - substâncias perigosas para o Homem e o ambiente - quando colocadas no mercado.   - - Equipamentos dotados de visor   - - - -   - Decreto-Lei n.º349/93, de 1 de Outubro – - Prescrições mínimas de segurança e de saúde - respeitantes ao trabalho com equipamentos - dotados de visor,   - - - - -   - Portaria n.º 989/93, de 6 de Outubro – - Prescrições mínimas de segurança e de saúde - respeitantes ao trabalho com equipamentos - dotados de visor (Regulamenta o Decreto-Lei - n.º349/93, de 1 de Outubro).   - - Movimentação manual de cargas   - - 1 - Decreto-Lei n.º330/93 de 25 de Outubro – - Relativa às prescrições mínimas de segurança - e de saúde na movimentação manual de cargas. -   - -   - 4. NORMALIZAÇÃO APLICÁVEL   -   - Na realização da avaliação de riscos laborais - foi considerada além da legislação, também a - normalização relativa à Segurança, Higiene e - Saúde do Trabalho.   - 4.1 Normalização portuguesa   - - 1 - Norma Portuguesa (NP) 3992:1994 - - Sinalização contra incêndio. Sinais de - segurança;   - - - 2 - NP EN 2:1993 - Classes de fogos;   - - - 3 - NP 1800:1981 - Segurança contra incêndios. - Agentes extintores. Selecção segundo as - classes de fogos;   - - - 4 -   - - - 5 - NP 3064:1988 - Segurança contra incêndio. - Utilização dos extintores de incêndio - portáteis;   - - - 6 - NP 4280:1995 - Segurança contra incêndios. - Sinalização de dispositivos de combate a - incêndio;   - - - 7 - NP 4413:2002 - Manutenção de extintores;   - - - 8 - NP EN 2:1993 - Classes de fogos;   - - - 9 - NP EN 1866: 2000 - Extintores de incêndio - móveis;   - - - 10 - NP EN 869:1998 - Mantas de incêndio;   - - - 11 - NP EN 671-1:2003 - Instalações fixas de - combate a incêndio – Sistemas armados com - mangueiras.   - -   - 4.2 Normalização internacional   - - 1 - - International Organization of - Standardization (ISO) 8995: - 2002 - Lighting of Indoor Work Places; -   - - - - 1 - ISO 9241-5:1998 - Ergonomic requirements for - Office work with visual display terminals - (VDTS) Part 5: Workstation layout and - postural requirements;   - - - 2 - Norma Belga NBN S26001: 1984 - Chair-desk - working position – Basic principles;   - - - 3 - Norma Belga NBN S26002: 1984 - Chair-desk - working position-Dimensions and design - requirements.   - -   -   - 5. OBRIGAÇÕES LEGAIS   -   - De acordo com o Capítulo IV da Lei nº99/2003 de - 27 de Agosto são estabelecidas obrigações legais - para o empregador e trabalhador.   -   -   - 5.1 Obrigações do empregador   - De acordo com o artigo 273º da Lei nº99/2003 de - 27 de Agosto o empregador tem de:   - - - -   - Identificar os riscos previsíveis, combatendo-os - na origem, anulando-os ou limitando os seus - efeitos;   - - - - -   - Avaliar os riscos para a segurança e saúde dos - trabalhadores, com a adopção de convenientes - medidas de prevenção;   - -   -   - - - -   - Assegurar que a exposição a agentes químicos, - físicos e biológicos não constituam risco para a - saúde;   - - - - -   - Considerar a componente técnica, organização do - trabalho, as relações sociais e os factores - materiais na planificação da prevenção;   - - - - -   - Ter em conta os trabalhadores e terceiros - susceptíveis de serem abrangidos pelos riscos e - realização de trabalhos;   - - - - -   - Dar prioridade à protecção colectiva em relação - às medidas de protecção individual;   - - - - -   - Organizar o trabalho, procurando eliminar - eventuais efeitos nocivos do trabalho monótono e - cadenciado;   - - - - - -   - Assegurar a vigilância adequada da saúde dos - trabalhadores em função - - - dos riscos a que se encontram expostos; -   - - - - -   - Estabelecer medidas, identificar trabalhadores - responsáveis e assegurar contactos necessários - com entidades exteriores em matéria de primeiros - socorros, combate a incêndios e evacuação dos - trabalhadores;   - - - - -   - Permitir unicamente a trabalhadores com aptidão - e formação adequadas o acesso (apenas durante o - tempo necessário) a zonas de risco grave;   - - - - -   - Adoptar medidas e dar instruções que permitam - aos trabalhadores em caso de perigo grave ou - eminente que não possa ser evitado, cessar a sua - actividade ou afastar-se imediatamente do local - de trabalho, sem que possam retomar a actividade - enquanto persistir o perigo;   - - - - -   - Substituir o que é perigoso pelo que é isento de - perigo ou menos perigoso;   - - - - -   - Dar instruções adequadas aos trabalhadores;   - - - - -   - Ter em consideração se os trabalhadores têm - conhecimentos e aptidões em matéria de SHST que - lhes permita exercer com segurança as tarefas - incumbidas.   - -   -   - 5.2 Obrigações do trabalhador   - De acordo com o artigo 274º da Lei nº99/2003 de - 27 de Agosto os trabalhadores têm de:   - - - -   - Cumprir prescrições de SHST estabelecidas e - instruções determinadas pelo empregador;   - - - - -   - Zelar pela sua segurança e saúde, bem como pela - das outras pessoas que possam ser afectadas - pelas suas acções ou omissões no trabalho;   - - - - -   - Utilizar correctamente máquinas, aparelhos, - instrumentos, substâncias perigosas e outros - equipamentos e meios postos à sua disposição - (equipamento de protecção colectiva e - individual) e cumprir os procedimentos de - trabalho estabelecidos;   - - - - -   - Cooperar na melhoria do sistema de SHST;   - - - - -   - Comunicar imediatamente (ao superior - hierárquico) as avarias e deficiências por si - detectadas que se afigurem susceptíveis de - originar perigo grave e iminente (se não for - possível estabelecer contacto, adoptar as - medidas e instruções estabelecidas), assim como - qualquer defeito verificado nos sistemas de - protecção;   - - - - -   - Adoptar as medidas e instruções estabelecidas em - caso de perigo grave e iminente, se não for - possível estabelecer contacto imediato com o - superior hierárquico ou com os trabalhadores que - desempenhem funções específicas nos domínios da - segurança, higiene e saúde do trabalho.   - -   -   - 6. EQUIPAMENTOS UTILIZADOS   - No decorrer da auditoria são realizadas medições - relativas aos níveis de iluminância, humidade - relativa, temperatura do ar, velocidade do ar e - do nível sonoro contínuo equivalente.   - Na realização das referidas medições são - utilizados os seguintes equipamentos - (devidamente calibrados):   - - - -   - Luxímetro (Chauvin Arnoux Physics Line CA 811); -   - - - - -   - Termo-higrómetro (Chauvin Arnoux Physics Line CA - 846);   - - - - -   - Sonómetro (Cesva SC – 15 c Classe 2).   - -   - 7. RISCOS LABORAIS   -   - 7.1 Classificação dos riscos profissionais   - Os riscos profissionais encontram-se - relacionados com a Segurança, a Higiene, a - Ergonomia e a Psicossociologia do Trabalho.   - - Segurança do Trabalho - : contacto directo/indirecto com a - electricidade, projecção de fragmentos ou - partículas. -   - - - Higiene do Trabalho - : -   - - - Riscos físicos - : exposição a ruído, vibrações, radiações - (ionizantes e não ionizantes), condições - inadequadas de iluminação; -   - - - Riscos químicos - : exposição a agentes químicos no estado - sólido (poeiras, fibras e fumos), líquido - (aerossóis e neblinas) e gasoso (gases e - vapores); -   - - - Riscos biológicos - : exposição a contaminantes biológicos - (vírus, bactérias, fungos e parasitas). -   - - - Ergonomia do Trabalho - : manipulação manual de cargas, adopção de - posturas incorrectas. -   - - - Psicossociologia do Trabalho - : realização de trabalho monótono e/ou - complexo, atendimento público, existência de - conflitos interpessoais. -   - -   -   - 7.2 Valoração dos riscos   - A valoração dos riscos associados as perigos - identificados tem como objectivo a definição de - prioridades da execução das medidas preventivas - (hierarquização dos riscos).   - - Para realizar a valoração de um risco - laboral é necessário atender à - probabilidade - de ocorrência (quantas vezes pode ocorrer?) - e da estimativa da - severidade - (gravidade) das consequências da sua - materialização (que dano/lesão pode - resultar?). -   - - As consequências de um risco laboral podem ser - caracterizadas em danos muito leves, em lesões - leves, lesões graves ou lesões muito graves ou - morte.   - No seguinte quadro encontram-se descritos alguns - exemplos de consequências de acordo com o grau - de severidade.   -   - - - - - - - SEVERIDADE (S)   - - - CONSEQUÊNCIAS PREVISÍVEIS   - - - - - Danos muito leves   - - - - Pequenos ferimentos   - - Dor de cabeça ou outros - transtornos leves que não causem - baixa   - - Desconforto, fadiga visual   - - Em geral, lesões ou - transtornos que não requeiram - tratamento médico ou baixa - médica   - - - - - Lesão leve   - - - - Contusões, cortes - superficiais, entorses, - distensões   - - Irritações   - - Pequenas queimaduras - superficiais   - - Em geral, lesões ou - transtornos que requerem - tratamento médico e podem - ocasionar em alguns casos baixa - de curta duração   - - - - - Lesão grave   - - - - Lacerações   - - Queimaduras extensas   - - Comoções/Abalos físicos   - - Pequenas fracturas   - - Doença crónica que conduza a - uma incapacidade menor - (diminuição da audição, - dermatoses, asma)   - - Transtornos - músculo-esqueléticos   - - - - - Lesão muito grave/mortal   - - - - Amputações, lesões múltiplas   - - Facturas maiores   - - Intoxicações   - - Cancro   - - Doenças crónicas que afectam - severamente a vida   - - Incapacidades permanentes   - - Invalidez   - - Morte   - - - - -   -   -   - Um risco laboral pode ser classificado em - improvável, possível, provável ou inevitável, de - acordo com a probabilidade de se vir a - materializar; como se pode verificar no quadro - seguinte.   -   - - - - - - - PROBABILIDADE (P)   - - - CRITÉRIOS APLICADOS   - - - - - Improvável   - - - - Extremamente raro, ainda não - acorreu   - - Não existe exposição ao perigo - em condições normais de trabalho - ou é muito esporádica   - - O dano não é previsível que - ocorra   - - - - - Possível   - - - - É raro que possa ocorrer   - - Se já ocorreu alguma vez   - - Pode-se apresentar em - determinadas circunstâncias   - - A exposição ao perigo é - ocasional   - - O dano ocorreu várias vezes   - - - - - Provável   - - - - Não será estranho que ocorra o - dano   - - Já ocorreu em algumas - situações   - - Existência de vários - incidentes ou acidentes pela - mesma causa   - - Os sistemas e medidas - aplicadas para o controlo dos - riscos não impedem que este se - manifeste em qualquer momento da - exposição   - - O dano ocorrerá em algumas - ocasiões   - - A exposição ao perigo é - frequente ou afecta bastante - pessoas   - - - - - Inevitável   - - - - É o resultado mais provável - quando existe uma exposição - continuada ou afecta a muitas - pessoas   - - Ocorrerá a médio ou a longo - prazo   - - O dano ocorrerá sempre ou - quase sempre   - - - - -   - Com base na frequência da exposição e nas - consequências de um risco, é possível construir - uma matriz de falhas, na qual podem ser - atribuídas cores e números que evidenciem os - diferentes níveis de valoração do risco, como se - pode verificar no quadro seguinte.   -   - - - - - - - -   - - -   - PROBABILIDADE DE MATERIALIZAÇÃO - DO RISCO   -   - - - - - GRAU DE SEVERIDADE POSSÍVEL   - - - IMPROVÁVEL   - 1   - - - POSSÍVEL   - 2   - - - PROVÁVEL   - 3   - - - INEVITÁVEL   - 4   - - - - - DANOS MUITO LEVES   - 1   - - - IRRELEVANTE   - 1   - - - MUITO BAIXO   - 2   - - - MUITO BAIXO   - 3   - - - BAIXO   - 4   - - - - - LESÃO LEVE   - 2   - - - MUITO BAIXO   - 2   - - - BAIXO   - 4   - - - MÉDIO   - 6   - - - ALTO   - 8   - - - - - LESÃO GRAVE   - 3   - - - MUITO BAIXO   - 3   - - - MÉDIO   - 6   - - - ALTO   - 9   - - - MUITO ALTO   - 12   - - - - - LESÃO MUITO GRAVE OU MORTAL   - 4   - - - BAIXO   - 4   - - - ALTO   - 8   - - - MUITO ALTO   - 12   - - - EXTREMAMENTE ALTO   - 16   - - - - -   -   -   -   - A determinação da valoração do risco permite - hierarquizar as intervenções, definir as acções - e estabelecer prazos de execução, como se - exemplifica no seguinte quadro:   -   - - - - - - - VALORAÇÃO DO RISCO   - - - RECOMENDAÇÕES   - - - - - Irrelevante   - - - Não é necessário estabelecer - nenhuma medida   - - - - - Muito baixo   - - - Não é necessário estabelecer - medidas adicionais às existentes -   - - - - - Baixo   - Prioridade: Baixa   - - - Controlar a situação que pode - materializar o risco   - - - - - Médio   - Prioridade: Média   - - - Verificar periodicamente a - eficácia das medidas de controlo - e melhorar a acção preventiva a - médio prazo (se as consequências - poderem ser muito graves ou - mortais, o prazo deve ser - reduzido)   - - - - - Alto   - Prioridade: Média/Alta   - - - Devem-se implementar medidas - para reduzir o risco a curto - prazo (se as consequências - poderem ser muito graves ou - mortais, o prazo deve ser - reduzido)   - - - - - Muito alto   - Prioridade: Alta   - - - Adoptar medidas provisórias - imediatas e definitivas para a - redução do risco a muito curto - prazo.   - Se o trabalho não se realiza - habitualmente, não se deve - iniciar sem que haja redução do - risco. Avaliar as medidas - adoptadas   - - - - - Extremamente alto   - Prioridade: Actuação imediata   - - - Não começar ou continuar o - trabalho até que se reduza o - risco. É necessário avaliar o - risco, uma vez corrigido.   - - - - -   - Alguns riscos laborais podem necessitar da - realização de estudos específicos, realizados de - acordo com os critérios estabelecidos na - legislação e normativa portuguesa e - internacional. Nesta situação, os riscos - laborais detectados podem ser classificados como - risco controlado, semi-controlado, incontrolado - e indeterminado, como é mostrado na tabela - seguinte.   - - - - - - - - - RISCOS DE HIGIENE, - ERGONOMICOS OU PSICOSSOCIAIS - DO TRABALHO   - - - CLASSIFICAÇÃO   - - - OBSERVAÇÕES   - - - - - Risco analisado/documentado. -   - Informação suficiente.   - - - - - - - - - Controlado   -   - - - As medidas - de controlo - existentes - são - adequadas   - - - - - Incontrolado -   - - - As medidas - de controlo - são - inexistentes, - insuficientes - ou - inadequadas. -   - - - - - - - - - Risco não - estudado/analisado.   - Informação insuficiente.   - - - Indeterminado   - - - É necessário realizar estudo - específico   - - - - -   - - Um risco analisado e documentado, é aquele que - tendo sido objecto de uma avaliação específica e - que se encontra documentado, registado e - disponível na empresa.   - - Um risco que foi analisado pode encontrar-se - controlado ou incontrolado - , sendo esta última situação referente ao - não cumprimento das medidas de controlo - aconselhadas nos - estudos realizados e à não realização de - novos estudos com a periodicidade - obrigatória. -   - - - Se não existe informação suficiente para - determinar a magnitude ou nível do risco e - poder adoptar as medidas adequadas, - classifica-se como risco - Indeterminado - . -   - -   -   -   - 8. AVALIAÇÃO DE RISCOS LABORAIS   -   -   -   - Com base na informação recolhida no decorrer da - auditoria, foram elaboradas as tabelas de riscos - laborais que a seguir se apresentam, sendo estas - elaboradas por trabalhador (ou grupo de - trabalhadores com actividades semelhantes) e - para as instalações.   - Para cada um dos riscos identificados são - aconselhadas medidas preventivas e/ou - correctivas, de acordo com a legislação e - normativa vigente, tendo em vista a sua - eliminação, redução ou controlo para níveis - aceitáveis.   - - - - -   - - - - - - - -   - - Avaliação Periódica de Riscos Laborais -   -   -   -   -   - - - -   -   -   -   -   -   -   -   -   -   -   - Genérico   - Riscos comuns às áreas Administrativa   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 1 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - 3   - - - 2   - - - 6   - MÉDIO   - - -   - - 1 - Risco ergonómico devido à - postura na utilização de - equipamentos dotados de - visor   - -   - - 1 - Formar os trabalhadores - sobre a utilização dos - equipamentos dotados de - visor (Decreto Lei nº 349/93 - – art. 8º).   - - Devido ao tempo de exposição aos - factores de risco inerentes ao - trabalho e ao tempo de - interacção com ecrãs de - visualização, devem ser - garantidas condições básicas - para que os colaboradores possam - executar as suas tarefas com o - máximo de conforto, garantindo - níveis de produtividade.   - - 1 - - Disponibilizar a - todos - os trabalhadores - cadeiras que: garantam - ajustabilidade (altura e - apoios) e disponham de - apoio para os braços - (ISO 9241:1997 – - Ergonomics requirements - for office work with - visual terminals) -   - - - - - - -   -   -   -   -   -   -   -   -   -   -   -   -   -   - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 2 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - 3   - - - 2   - - - 6   - MÉDIO   - - -   -   - - 1 - Risco de exposição a - condições inadequadas de - iluminação   - - - 1 - As fontes de iluminação - devem ser de intensidade - uniforme e não devem - provocar contrastes muito - acentuados, encandeamento, - excessivo aquecimento, - cheiros, fumos ou gases - incómodos, tóxicos ou - perigosos (Decreto Lei nº - 243/86 – art. 14º);   - - - 2 - O valor de iluminância deve - ser no mínimo de 500 lux na - área focal de trabalho e de - 300 lux no envolvimento para - actividade de carácter (ISO - 8995 –Lighting of Indoor - Work Places);   - - - 3 - - A instalação eléctrica - (…) e deve assegurar que - a sua utilização não - constitua factor de - risco para os - trabalhadores, por - contacto directo ou - indirecto - ( - Portaria 987/93 art. 3º - - 1) -   - - - Todas as lâmpadas existentes nas - instalações deverão estar - devidamente protegidas.   - - - - - 3   - - - 2   - - - 6   - MÉDIO   - - -   - - 1 - Risco de incêndio   - -   - - 1 - - Todos os - estabelecimentos - comerciais devem dispor - de meios de primeira - intervenção apropriados, - colocados perto dos - acessos às escadas ou - saídas, nos caminhos de - evacuação e na - proximidade dos locais - de maior risco ( - Decreto-Lei 368/99 - - ponto 9 do Anexo - ); -   - - - - 2 - - Manter o material de - detecção e combate a - incêndios - permanentemente - acessível - (Decreto Lei n.º243/86 – - art.36º-1) - ; -   - - - Todos os extintores existentes - nas instalações deverão estar - posicionados a 1,20 m do chão - (manípulo)   - - - - -   -   -   - - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 3 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - 4   - - - 1   - - - 4   - BAIXO   - - -   - - 1 - Risco de choque contra - objectos imóveis   - - - 1 - Manter o local de trabalho - arrumado (Decreto Lei - n.º441/91 – art.15ºb);   - - - 1 - Assegurar que as vias de - passagem se encontram - permanentemente - desobstruídas (Portaria - n.º987/93 – art.4º.)   - - - - - - 2   - - - 2   - - - 4   - BAIXO   - - - -   -   - - - 1 - Risco de desconforto térmico -   - - - 1 - O valor de temperatura deve - situar-se no intervalo de - valores recomendados (18 a - 22ºC, podendo atingir os - 25ºC em determinadas - condições climatéricas) - (Decreto Lei n.º243/86 – - art.11º-1a);   - - - 2 - O valor de humidade relativa - da atmosfera de trabalho - deve situar-se no intervalo - de valores recomendados (50 - a 70%) (Decreto-Lei - n.º243/86 – art.11º- 1b).   - - - Os valores de temperatura em - toda a área de escritórios - variaram entre - 21,1 ºC - e - 22 ºC - . Todos os valores - apresentados estão de acordo - com os valores recomendáveis - para o tipo de actividade - que aí se desenvolve. -   - - - Os valores de humidade - relativa da atmosfera de - trabalho em toda a área de - escritórios variaram entre - 27,3% - e - 29,2%. - Todos os valores - apresentados são inferiores - aos valores recomendáveis - para o tipo de actividade - que aí se desenvolve. -   - - - - - -   -   -   -   - - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 4 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - 2   - - - 2   - - - 4   - BAIXO   - - -   - - 1 - Risco de exposição ao ruído -   - - - 1 - - O empregador assegura - que a exposição dos - trabalhadores ao ruído - durante o trabalho seja - reduzida ao nível mais - baixo possível e, em - qualquer caso, não - superior aos valores - limite de exposição de - 87 dB (A) e 140 dB (C) ( - Decreto Lei nº 182/2006 - -Art. 8º 1 - ); -   - - - - 1 - - O nível sonoro contínuo - equivalente médio obtido - (nas áreas - administrativas) variou - entre - 42 dB(A) e 70 dB (A), - pelo que (e em condições - normais de - funcionamento) a - Exposição pessoal diária - ao ruído, a média - semanal dos valores - diários da exposição - pessoal ao ruído e o - nível de pressão sonora - de pico deverá ser - inferior aos valores - limite. -   - - - - - - - 2   - - - 2   - - - 4   - BAIXO   - - -   - - 1 - Risco de contacto eléctrico - na utilização da instalação - e equipamentos eléctricos   - - - 1 - Toda a instalação eléctrica - deverá encontrar-se de - acordo com a Portaria nº - 949-A/2006 de 11 de Setembro - de 2006, que aprova as - regras técnicas das - instalações eléctricas de - baixa tensão.   - - Os colaboradores deverão estar - sensibilizados para a utilização - correcta da electricidade, de - forma a evitar situações de - sobrecarga das fontes de energia - (fichas triplas e extensões - sobrecaregadas)   - - - - - 2   - - - 2   - - - 4   - BAIXO   - - -   - - 1 - Risco de contacto com - objectos perfurantes e/ou - cortantes   - -   - - 1 - Assegurar a sua substituição - quando apresentarem um - elevado estado de degradação - (Decreto Lei n.º441/91 – - art.15ºb)   - - - 2 - Mantê-los arrumados após - cada utilização (Decreto Lei - n.º441/91 – art.15ºb)   - - - - - -   -   - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 5 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - 2   - - - 2   - - - 4   - BAIXO   - - -   - - 1 - Risco de queda ao mesmo - nível   - - - 1 - - Manter o pavimento dos - locais de trabalho - isentos de obstáculos - que possam provocar - quedas ( - Portaria n.º987/93 – - art.10º - ) -   - - - Identificar as áreas de trabalho - onde se verifica acumulação de - cablagens diversas em espaços de - circulação e rotear devidamente - (ou colocar no interior de calha - técnica) os referidos cabos para - que estes não representem risco - de queda para os trabalhadores   - - -   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Inexistência de sinalização - adequada de segurança e - saúde   - - - 1 - - Os sinais devem ser - instalados em local bem - iluminado, a altura e em - posição apropriadas, - tendo em conta os - impedimentos à sua - visibilidade desde a - distância julgada - conveniente ( - Portaria n.º1456-A/95 – - Art. 6º-1 - ); -   - - - - 2 - Limpar e verificar - regularmente os meios de - sinalização de segurança - (Portaria nº 1456-A/95 – - Art. 4º);   - - - 3 - Informar, consultar e formar - os trabalhadores sobre a - sinalização de segurança e - saúde (Decreto Lei nº 141/95 - – Art. 9º).   - - Assegurar que a sinalização de - segurança e emergência se - encontra permanentemente - actualizada   -   - - -   - - - - -   -   -   -   -   - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 6 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Existência de iluminação de - emergência de segurança   - - - 1 - A instalação de iluminação - de emergência de segurança - deverá permitir, em caso de - avaria da instalação normal, - a evacuação segura e fácil - do público para o exterior e - a execução das manobras - respeitantes à segurança e à - intervenção de socorros - (Portaria nº 740/74 – art. - 446º);   - - - 2 - A instalação de iluminação - de emergência deverá - assegurar a iluminação de - ambiente e a de circulação - (Portaria nº 740/74 – art. - 446º   - - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Organização dos meios de - evacuação e emergência   - - - 1 - Nos caminhos de evacuação - não devem ser colocados - obstáculos susceptíveis de - dificultarem a circulação e - poderem também constituir um - risco de propagação de - incêndio (Decreto Lei nº - 368/99 de 18 de Setembro - Anexo 2.1.5);   - - - 2 - - Assegurar que os - colaboradores se - encontram - suficientemente - instruídos sobre os - planos de evacuação dos - locais de trabalho - (Decreto Lei n.º 243/86 - – art.37º-1); -   - - - - 3 - As vias normais e de - emergência têm de estar - permanentemente - desobstruídas e em condições - de utilização, devendo o - respectivo traçado conduzir, - o mais rapidamente possível, - a áreas ao ar livre ou a - zonas de segurança (Portaria - nº 987/93 – 4º – 1);   - - - 4 - A instalação de cada posto - de trabalho deve permitir a - evacuação rápida e em máxima - segurança dos trabalhadores - (Portaria nº 987/93 – 4º – - 3).   - - - - - -   -   - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 7 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Utilização de equipamentos - de trabalho (máquinas, - ferramentas ou instalações) -   - -   - - 1 - O empregador tem de - assegurar que os - equipamentos de trabalho são - adequados ou - convenientemente adaptados - ao trabalho a efectuar; - atender às condições e - características do trabalho - e aos riscos existentes na - escolha dos equipamentos de - trabalho; considerar os - postos de trabalho, posição - dos trabalhadores e os - princípios ergonómicos no - decorrer da utilização dos - equipamentos; e assegurar a - sua adequada manutenção - (Decreto Lei nº 50/2005 – - art. 3º)   - - - 2 - O empregador deve prestar a - trabalhadores e - representantes para a - segurança, higiene e saúde - do trabalho a informação - adequada sobre os - equipamentos de trabalho - utilizados (Decreto Lei nº - 50/2005 – art. 8º);   - - - 3 - O empregador deve consultar - por escrito, previamente e - em tempo útil, os - representantes dos - trabalhadores ou, na sua - ausência, os trabalhadores - sobre os equipamentos de - trabalho utilizados, pelo - menos duas vezes por ano - (Decreto Lei nº 50/2005 – - art. 9º)   - - - - - -   -   -   -   -   -   -   -   -   -   -   -   - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 8 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Existência de armário, caixa - ou bolsa com conteúdo mínimo - destinado aos primeiros - socorros   - -   - - 1 - O conteúdo dos armários, - caixas ou bolsas, deve ser - mantido em condições de - assepsia, convenientemente - conservado, etiquetado e - imediatamente substituído - após a sua utilização - (Decreto Lei n.º243/86 – - art.º28º-2);   - - - 2 - Deverão existir instruções - claras e simples para os - primeiros cuidados a pôr em - prática em caso de - emergência junto dos - armários, caixas ou bolsas - de primeiros socorros - (Decreto Lei n.º243/86 – - art.º28º-4).   - - - - - -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 9 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Risco de exposição a - contaminantes químicos e - biológicos   - - - 1 - O empregador deve assegurar - que as exposições aos - agentes químicos, físicos e - biológicos nos locais de - trabalho não constituam - risco para a saúde dos - trabalhadores (Lei nº 99/03 - – Art.273º -2c);   - - - 2 - Os níveis de concentração de - substâncias nocivas - existentes no ar não podem - ultrapassar os definidos em - legislação específica - (Portaria nº 987/93 – art.6º - - 5);   - - - 3 - As instalações e - equipamentos devem possuir - um plano de manutenção - preventiva que estabeleça - claramente as tarefas de - manutenção previstas, - nomeadamente o registo das - análises periódicas da - Qualidade do Ar Interior, - com indicação do técnico ou - técnicos que as realizaram - (Decreto Lei nº 79/2006 – - Art.19º- 2).   - - - 4 - Limpar e desinfectar todo o - equipamento no mínimo duas - vezes por ano e Verificar - regularmente o estado de - limpeza dos filtros e - proceder à sua limpeza - sempre que se justifique - (Direcção Geral da Saúde);   - - - 5 - - Realizar avaliações - microbiológicas - periódicas no interior - do sistema de ar - condicionado. - (Decreto-Lei 78/2006 e - Decreto-Lei 79/2006) - - próxima auditoria a - realizar até ao final de - 2009 - . -   - - - As embalagens de toner vazias - devem ser sempre armazenar em - local afastado dos locais de - trabalho   -   - - - - -   -   -   -   -   -   -   - - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 10 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Existência de informação no - domínio da segurança, - higiene e saúde do trabalho -   - - - 1 - - Garantir a existência de - informação actualizada - sobre (Lei nº 99/2003 de - 27 de Agosto - art. 272 - º): -   - - - - 1 - Riscos para a segurança e - saúde, medidas de protecção - e de prevenção e a forma - como se aplicam;   - - - 2 - Medidas e instruções a - adoptar em caso de perigo - grave e iminente;   - - - 3 - Medidas de primeiros - socorros, de combate a - incêndios e de evacuação dos - trabalhadores em caso de - sinistro, bem como os - trabalhadores ou serviços - encarregados de as pôr em - prática.   - - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Formação no domínio da - segurança, higiene e saúde - do trabalho   - -   - - 1 - - Proporcionar formação - adequada e suficiente no - domínio da segurança, - higiene e saúde do - trabalho, tendo em conta - as respectivas funções e - o posto de trabalho ( - Lei nº 35/04 – art. 216º - ); -   - - - - 2 - - Formar em número - suficiente os - trabalhadores - responsáveis pela - aplicação das medidas de - primeiros socorros, de - combate a incêndios e de - evacuação de - trabalhadores, bem como - facultar-lhes o material - adequado ( - Lei nº 35/04 – art. 217º - ). -   - - - - - - -   -   -   -   -   -   -   - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - -   - - EMPRESA - : Auchan -   - - - -   - - DATA DA AVALIAÇÃO - : 6 de Março de 2008 -   - - - - - AVALIAÇÃO: INICIAL - - ¨ - PERIÓDICA - þ - -   - - - - - -   - ESTABELECIMENTO: Coimbra   - - -   - - DATA DA PRÓXIMA - : 25 de Setembro de 2008 -   - - - - REALIZADA POR: Sónia Campos   - SIPRP – Sociedade Ibérica de - Prevenção de Riscos - Profissionais   - - - - - - POSTO DE TRABALHO - : - Genérico Área Administrativa -   - - - - Página 11 de 11   - - - - - SEV.   - (S)   - - - PROB.   - (P)   - - - VALOR RISCO   - (S x P)   - - - RISCO / CONDIÇÕES ANÓMALAS /   - / ACÇÕES DE CONTROLO OU REDUÇÃO - DO RISCO   - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Representante dos - trabalhadores para a - segurança, higiene e saúde - no trabalho   - -   - - 1 - - Os trabalhadores ou o - sindicato que tenha - trabalhadores - representados na empresa - promovem a eleição dos - representantes dos - trabalhadores para a - segurança, higiene e - saúde do trabalho ( - Lei nº 35/04 – art. 266º - ). -   - - - - - - - -   - - - -   - - - INDETERMINADO   - - -   - - 1 - Comissão de higiene e - segurança no trabalho   - -   - - 1 - - Podem ser criadas - comissões de higiene e - segurança no trabalho de - composição paritária - (Lei - nº 35/04 – art. 215º - ). -   - - - - - - -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   - - - - - -   -   -   - - - - - - Avaliação Periódica de Riscos Laborais -   -   - - - 113 - -   - - - -   -   - 9. PLANO DE ACTUAÇÃO   -   - A partir dos resultados da avaliação de riscos, - é elaborado um outro documento (Plano de - Actuação), que inclui a listagem das acções que - deverão ser realizadas de modo a eliminar, - reduzir ou controlar os riscos detectados.   - - Este Plano permitirá auxiliar a - AUCHAN - - - Loja de Coimbra - na programação e acompanhamento das - referidas acções. -   - -   -   - 10. CONSIDERAÇÕES FINAIS   -   - - A equipa técnica de Segurança e Higiene do - Trabalho da SIPRP agradece a colaboração de - todos os colaboradores da - AUCHAN - - - Loja de Coimbra - durante a realização desta auditoria, - ficando à disposição para qualquer - esclarecimento. -   - -   -   -   - Lisboa, 29 de Abril de 2008   -   - - - - - -   - Sónia Campos   - Ergonomista   - Téc. Sup. Seg. Hig. do Trabalho -   - (CAP nº 0601/6505/02)   - - - - -   -   -   -   - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2.xsl b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2.xsl deleted file mode 100644 index 89c379af..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2.xsl +++ /dev/null @@ -1,4391 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ATRIUM SALDANHA   - - - Praça Duque de Saldanha, 1 – 9º G   - - - 1050 – 094 Lisboa   - - - Telefone (+351) 213 504 540   - - - Fax (+351) 213 504 549   - - - geral@siprp.pt   - - - www.siprp.com   - - - - - Lisboa   - - - - - de - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - Relatório - - -   - - -   - - -   - - - - - - - - -   - - -   - - - - - - - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - - ÍNDICE - - - - 1. INTRODUÇÃO - - - - - - - 2. DADOS DA EMPRESA - - - - - - - 3. LEGISLAÇÃO APLICÁVEL - - - - - - - 3.1 Legislação de aplicação geral - - - - - - - 3.2 Legislação específica - - - - - - - 4. NORMALIZAÇÃO APLICÁVEL - - - - - - - 4.1 Normalização portuguesa - - - - - - - 4.2 Normalização internacional - - - - - - - 5. OBRIGAÇÕES LEGAIS - - - - - - - 5.1 Obrigações do empregador - - - - - - - 5.2 Obrigações do trabalhador - - - - - - - 6. EQUIPAMENTOS UTILIZADOS - - - - - - - 7. RISCOS LABORAIS - - - - - - - 7.1 Classificação dos riscos profissionais - - - - - - - 7.2 Valoração dos riscos - - - - - - - 8. AVALIAÇÃO DE RISCOS LABORAIS - - - - - - - 9. PLANO DE ACTUAÇÃO - - - - - - - 10. CONSIDERAÇÕES FINAIS - - - - - -   - - -   - - - - 1. INTRODUÇÃO   - - -   - - - A entidade empregadora deve tomar todas as - medidas necessárias para a defesa da segurança e - saúde dos seus trabalhadores, mediante a criação - de um sistema organizado, dotado dos meios - necessários, que deve abranger as medidas de - eliminação e de controlo dos riscos, assim como - de formação, informação e consulta a empreender. -   - - - - De acordo com a Lei nº 35/2004 de 29 de - Julho, que contém os princípios que visam - promover a segurança, higiene e saúde do - trabalho, o empregador deve - - - “Integrar no conjunto de actividades da - empresa … a avaliação dos riscos para a - segurança e saúde dos trabalhadores, com a - adopção de convenientes medidas de - prevenção.” - -   - - - Tendo em vista assegurar condições adequadas de - segurança, higiene e saúde dos trabalhadores, - são realizadas auditorias de segurança, no - decorrer das quais:   - - - - - - • - - - - - é recolhida informação através das - visitas aos locais de trabalho, do - diálogo estabelecido com os - trabalhadores ou através de outras - fontes de informação; - - - - - - - • - - - - - é listado o conjunto de factores de - risco inerentes às condições normais - de laboração ou aos acontecimentos - não planeados mas previsíveis;   - - - - - - - • - - - - - são identificados os trabalhadores - potencialmente expostos a riscos - resultantes dos factores de risco - identificados;   - - - - - - - • - - - - - é recolhida informação relativa à - existência de grupos específicos - (jovens, grávidas, puérperas, - lactantes);   - - - - - - - • - - - - - são identificados os trabalhadores - envolvidos em trabalhos proibidos, - condicionados ou não recomendados;   - - - - - - - • - - - - - são identificadas as situações de - perigo grave ou iminente.   - - - - - - A avaliação dos riscos laborais consiste - portanto, na análise estruturada de todos os - aspectos inerentes ao trabalho, concretizada - através da identificação, estimação e valoração - dos riscos existentes (com indicação dos - trabalhadores a eles expostos) e da definição - das medidas de prevenção ou protecção adequadas. -   - - -   - - - -   - - - 2. DADOS DA EMPRESA   - - -   - - - No dia - - - de - - de - - - - realizou-se a auditoria às instalações da - empresa - - - - – - - - , situada na - - - - - (cuja actividade desenvolvida é de - - ) para a avaliação das condições de - segurança, higiene e saúde do trabalho - existentes. - -   - - - - - - Para a realização da visita, a Técnica Superior - de Segurança e Higiene do Trabalho da Sociedade - Ibérica de Prevenção de Riscos Profissionais - Unipessoal Lda., obteve a colaboração e - acompanhamento de - - ( - - ) - - e - ( - - ) - - na prestação de informações relativas à - actividade desenvolvida e às condições de - trabalho existentes.   - - -   - - -   - - - 3. LEGISLAÇÃO APLICÁVEL   - - -   - - - A avaliação de riscos laborais realizada foi - baseada nas obrigações impostas pela legislação - portuguesa em vigor relativa à Segurança, - Higiene e Saúde do Trabalho.   - - -   - - - 3.1 Legislação de aplicação geral   - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - -   - - - 3.2 Legislação específica   - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - -   - - - 4. NORMALIZAÇÃO APLICÁVEL   - - -   - - - Na realização da avaliação de riscos laborais - foi considerada além da legislação, também a - normalização relativa à Segurança, Higiene e - Saúde do Trabalho.   - - - 4.1 Normalização portuguesa   - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - -   - - - 4.2 Normalização internacional   - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - -   - - - 5. OBRIGAÇÕES LEGAIS   - - -   - - - De acordo com o Capítulo IV da Lei nº99/2003 de - 27 de Agosto são estabelecidas obrigações legais - para o empregador e trabalhador.   - - -   - - -   - - - 5.1 Obrigações do empregador   - - - De acordo com o artigo 273º da Lei nº99/2003 de - 27 de Agosto o empregador tem de:   - - - - - - - - - - - - Identificar os riscos previsíveis, - combatendo-os na origem, anulando-os - ou limitando os seus efeitos;   - - - - - - - - - - > - - - - Avaliar os riscos para a segurança e - saúde dos trabalhadores, com a - adopção de convenientes medidas de - prevenção;   - - - - - - - - - - > - - - - Assegurar que a exposição a agentes - químicos, físicos e biológicos não - constituam risco para a saúde;   - - - - - - - - - - > - - - - Considerar a componente técnica, - organização do trabalho, as relações - sociais e os factores materiais na - planificação da prevenção;   - - - - - - - - - - > - - - - Ter em conta os trabalhadores e - terceiros susceptíveis de serem - abrangidos pelos riscos e realização - de trabalhos;   - - - - - - - - - - > - - - - Dar prioridade à protecção colectiva - em relação às medidas de protecção - individual;   - - - - - - - - - - > - - - - Organizar o trabalho, procurando - eliminar eventuais efeitos nocivos - do trabalho monótono e cadenciado;   - - - - - - - - - - > - - - - Assegurar a vigilância adequada da - saúde dos trabalhadores em função - dos riscos a que se encontram - expostos; - - - - - - - - - - > - - - - Estabelecer medidas, identificar - trabalhadores responsáveis e - assegurar contactos necessários com - entidades exteriores em matéria de - primeiros socorros, combate a - incêndios e evacuação dos - trabalhadores;   - - - - - - - - - - > - - - - Permitir unicamente a trabalhadores - com aptidão e formação adequadas o - acesso (apenas durante o tempo - necessário) a zonas de risco grave; -   - - - - - - - - - - > - - - - Adoptar medidas e dar instruções que - permitam aos trabalhadores em caso - de perigo grave ou eminente que não - possa ser evitado, cessar a sua - actividade ou afastar-se - imediatamente do local de trabalho, - sem que possam retomar a actividade - enquanto persistir o perigo;   - - - - - - - - - - > - - - - Substituir o que é perigoso pelo que - é isento de perigo ou menos - perigoso;   - - - - - - - - - - > - - - - Dar instruções adequadas aos - trabalhadores;   - - - - - - - - - - > - - - - Ter em consideração se os - trabalhadores têm conhecimentos e - aptidões em matéria de SHST que lhes - permita exercer com segurança as - tarefas incumbidas.   - - - - - -   - - -   - - - 5.2 Obrigações do trabalhador   - - - - - - - - - > - - - - De acordo com o artigo 274º da Lei - nº99/2003 de 27 de Agosto os - trabalhadores têm de:   - - - - - - - - - - > - - - - Cumprir prescrições de SHST - estabelecidas e instruções - determinadas pelo empregador;   - - - - - - - - - - > - - - - Zelar pela sua segurança e saúde, - bem como pela das outras pessoas que - possam ser afectadas pelas suas - acções ou omissões no trabalho;   - - - - - - - - - - > - - - - Utilizar correctamente máquinas, - aparelhos, instrumentos, substâncias - perigosas e outros equipamentos e - meios postos à sua disposição - (equipamento de protecção colectiva - e individual) e cumprir os - procedimentos de trabalho - estabelecidos;   - - - - - - - - - - > - - - - Cooperar na melhoria do sistema de - SHST;   - - - - - - - - - - > - - - - Comunicar imediatamente (ao superior - hierárquico) as avarias e - deficiências por si detectadas que - se afigurem susceptíveis de originar - perigo grave e iminente (se não for - possível estabelecer contacto, - adoptar as medidas e instruções - estabelecidas), assim como qualquer - defeito verificado nos sistemas de - protecção;   - - - - - - - - - - > - - - - Adoptar as medidas e instruções - estabelecidas em caso de perigo - grave e iminente, se não for - possível estabelecer contacto - imediato com o superior hierárquico - ou com os trabalhadores que - desempenhem funções específicas nos - domínios da segurança, higiene e - saúde do trabalho.   - - - - - -   - - - - 6. EQUIPAMENTOS UTILIZADOS   - - -   - - - No decorrer da auditoria são realizadas medições - relativas aos níveis de iluminância, humidade - relativa, temperatura do ar, velocidade do ar e - do nível sonoro contínuo equivalente.   - - - Na realização das referidas medições são - utilizados os seguintes equipamentos - (devidamente calibrados):   - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - -   - - -   - - - 7. RISCOS LABORAIS   - - -   - - -   - - - 7.1 Classificação dos riscos profissionais   - - - Os riscos profissionais encontram-se - relacionados com a Segurança, a Higiene, a - Ergonomia e a Psicossociologia do Trabalho.   - - - - Segurança do Trabalho - - - : contacto directo/indirecto com a - electricidade, projecção de fragmentos ou - partículas. - - - - - Higiene do Trabalho - - : - - - - Riscos físicos - - : exposição a ruído, vibrações, radiações - (ionizantes e não ionizantes), condições - inadequadas de iluminação; - - - - Riscos químicos - - : exposição a agentes químicos no estado sólido - (poeiras, fibras e fumos), líquido (aerossóis e - neblinas) e gasoso (gases e vapores); - - - - Riscos biológicos - - : exposição a contaminantes biológicos (vírus, - bactérias, fungos e parasitas). - - - - Ergonomia do Trabalho - - : manipulação manual de cargas, adopção de - posturas incorrectas. - - - - Psicossociologia do Trabalho - - : realização de trabalho monótono e/ou complexo, - atendimento público, existência de conflitos - interpessoais. - - -   - - - 7.2 Valoração dos riscos   - - - A valoração dos riscos associados as perigos - identificados tem como objectivo a definição de - prioridades da execução das medidas preventivas - (hierarquização dos riscos).   - - - Para realizar a valoração de um risco laboral é - necessário atender à - - probabilidade - - de ocorrência (quantas vezes pode ocorrer?) e da - estimativa da - - severidade - - (gravidade) das consequências da sua - materialização (que dano/lesão pode resultar?). - - - As consequências de um risco laboral podem ser - caracterizadas em danos muito leves, em lesões - leves, lesões graves ou lesões muito graves ou - morte.   - - - No seguinte quadro encontram-se descritos alguns - exemplos de consequências de acordo com o grau - de severidade.   - - -   - - - - - - - - - SEVERIDADE (S)   - - - - - CONSEQUÊNCIAS PREVISÍVEIS   - - - - - - - Danos muito leves   - - - - - - Pequenos ferimentos   - - - - Dor de cabeça ou outros - transtornos leves que não causem - baixa   - - - - Desconforto, fadiga visual   - - - - Em geral, lesões ou - transtornos que não requeiram - tratamento médico ou baixa - médica   - - - - - - - Lesão leve   - - - - - - Contusões, cortes - superficiais, entorses, - distensões   - - - - Irritações   - - - - Pequenas queimaduras - superficiais   - - - - Em geral, lesões ou - transtornos que requerem - tratamento médico e podem - ocasionar em alguns casos baixa - de curta duração   - - - - - - - Lesão grave   - - - - - - Lacerações   - - - - Queimaduras extensas   - - - - Comoções/Abalos físicos   - - - - Pequenas fracturas   - - - - Doença crónica que conduza a - uma incapacidade menor - (diminuição da audição, - dermatoses, asma)   - - - - Transtornos - músculo-esqueléticos   - - - - - - - Lesão muito grave/mortal   - - - - - - Amputações, lesões múltiplas   - - - - Facturas maiores   - - - - Intoxicações   - - - - Cancro   - - - - Doenças crónicas que afectam - severamente a vida   - - - - Incapacidades permanentes   - - - - Invalidez   - - - - Morte   - - - - - - -   - - -   - - - Um risco laboral pode ser classificado em - improvável, possível, provável ou inevitável, de - acordo com a probabilidade de se vir a - materializar; como se pode verificar no quadro - seguinte.   - - -   - - - - - - - - - PROBABILIDADE (P)   - - - - - CRITÉRIOS APLICADOS   - - - - - - - Improvável   - - - - - - Extremamente raro, ainda não - acorreu   - - - - Não existe exposição ao perigo - em condições normais de trabalho - ou é muito esporádica   - - - - O dano não é previsível que - ocorra   - - - - - - - Possível   - - - - - - É raro que possa ocorrer   - - - - Se já ocorreu alguma vez   - - - - Pode-se apresentar em - determinadas circunstâncias   - - - - A exposição ao perigo é - ocasional   - - - - O dano ocorreu várias vezes   - - - - - - - Provável   - - - - - - Não será estranho que ocorra o - dano   - - - - Já ocorreu em algumas - situações   - - - - Existência de vários - incidentes ou acidentes pela - mesma causa   - - - - Os sistemas e medidas - aplicadas para o controlo dos - riscos não impedem que este se - manifeste em qualquer momento da - exposição   - - - - O dano ocorrerá em algumas - ocasiões   - - - - A exposição ao perigo é - frequente ou afecta bastante - pessoas   - - - - - - - Inevitável   - - - - - - É o resultado mais provável - quando existe uma exposição - continuada ou afecta a muitas - pessoas   - - - - Ocorrerá a médio ou a longo - prazo   - - - - O dano ocorrerá sempre ou - quase sempre   - - - - - - -   - - - Com base na frequência da exposição e nas - consequências de um risco, é possível construir - uma matriz de falhas, na qual podem ser - atribuídas cores e números que evidenciem os - diferentes níveis de valoração do risco, como se - pode verificar no quadro seguinte.   - - -   - - - - - - - - - -   - - - - -   - - - PROBABILIDADE DE MATERIALIZAÇÃO - DO RISCO   - - - - - - - - GRAU DE SEVERIDADE POSSÍVEL   - - - - - IMPROVÁVEL   - - - 1   - - - - - POSSÍVEL   - - - 2   - - - - - PROVÁVEL   - - - 3   - - - - - INEVITÁVEL   - - - 4   - - - - - - - DANOS MUITO LEVES   - - - 1   - - - - - IRRELEVANTE   - - - 1   - - - - - MUITO BAIXO   - - - 2   - - - - - MUITO BAIXO   - - - 3   - - - - - BAIXO   - - - 4   - - - - - - - LESÃO LEVE   - - - 2   - - - - - MUITO BAIXO   - - - 2   - - - - - BAIXO   - - - 4   - - - - - MÉDIO   - - - 6   - - - - - ALTO   - - - 8   - - - - - - - LESÃO GRAVE   - - - 3   - - - - - MUITO BAIXO   - - - 3   - - - - - MÉDIO   - - - 6   - - - - - ALTO   - - - 9   - - - - - MUITO ALTO   - - - 12   - - - - - - - LESÃO MUITO GRAVE OU MORTAL   - - - 4   - - - - - BAIXO   - - - 4   - - - - - ALTO   - - - 8   - - - - - MUITO ALTO   - - - 12   - - - - - EXTREMAMENTE ALTO   - - - 16   - - - - - - -   - - -   - - - A determinação da valoração do risco permite - hierarquizar as intervenções, definir as acções - e estabelecer prazos de execução, como se - exemplifica no seguinte quadro:   - - -   - - - - - - - - - VALORAÇÃO DO RISCO   - - - - - RECOMENDAÇÕES   - - - - - - - Irrelevante   - - - - - Não é necessário estabelecer - nenhuma medida   - - - - - - - Muito baixo   - - - - - Não é necessário estabelecer - medidas adicionais às existentes -   - - - - - - - Baixo   - - - Prioridade: Baixa   - - - - - Controlar a situação que pode - materializar o risco   - - - - - - - Médio   - - - Prioridade: Média   - - - - - Verificar periodicamente a - eficácia das medidas de controlo - e melhorar a acção preventiva a - médio prazo (se as consequências - poderem ser muito graves ou - mortais, o prazo deve ser - reduzido)   - - - - - - - Alto   - - - Prioridade: Média/Alta   - - - - - Devem-se implementar medidas - para reduzir o risco a curto - prazo (se as consequências - poderem ser muito graves ou - mortais, o prazo deve ser - reduzido)   - - - - - - - Muito alto   - - - Prioridade: Alta   - - - - - Adoptar medidas provisórias - imediatas e definitivas para a - redução do risco a muito curto - prazo.   - - - Se o trabalho não se realiza - habitualmente, não se deve - iniciar sem que haja redução do - risco. Avaliar as medidas - adoptadas   - - - - - - - Extremamente alto   - - - Prioridade: Actuação imediata   - - - - - Não começar ou continuar o - trabalho até que se reduza o - risco. É necessário avaliar o - risco, uma vez corrigido.   - - - - - - -   - - - Alguns riscos laborais podem necessitar da - realização de estudos específicos, realizados de - acordo com os critérios estabelecidos na - legislação e normativa portuguesa e - internacional. Nesta situação, os riscos - laborais detectados podem ser classificados como - risco controlado, semi-controlado, incontrolado - e indeterminado, como é mostrado na tabela - seguinte.   - - -   - - - - - - - - - - RISCOS DE HIGIENE, ERGONOMICOS - OU PSICOSSOCIAIS DO TRABALHO   - - - - - CLASSIFICAÇÃO   - - - - - OBSERVAÇÕES   - - - - - - - Risco analisado/documentado.   - - - Informação suficiente.   - - - - - - - - - - - Controlado   - - -   - - - - - As medidas de - controlo - existentes são - adequadas   - - - - - - - Incontrolado   - - - - - As medidas de - controlo são - inexistentes, - insuficientes ou - inadequadas.   - - - - - - - - - - - Risco não estudado/analisado.   - - - Informação insuficiente.   - - - - - Indeterminado   - - - - - É necessário realizar estudo - específico   - - - - - -   - - Um risco analisado e documentado, é aquele que - tendo sido objecto de uma avaliação específica e - que se encontra documentado, registado e - disponível na empresa.   - - - - Um risco que foi analisado pode encontrar-se - - - controlado ou incontrolado - - - , sendo esta última situação referente ao - não cumprimento das medidas de controlo - aconselhadas nos - - - estudos realizados e à não realização de - novos estudos com a periodicidade - obrigatória. - -   - - - - Se não existe informação suficiente para - determinar a magnitude ou nível do risco e - poder adoptar as medidas adequadas, - classifica-se como risco - - - Indeterminado - - . -   - - -   - - - -   - - -   - - - 8. AVALIAÇÃO DE RISCOS LABORAIS   - - -   - - - Com base na informação recolhida no decorrer da - auditoria, foram elaboradas as tabelas de riscos - laborais que a seguir se apresentam, sendo estas - elaboradas por trabalhador (ou grupo de - trabalhadores com actividades semelhantes) e - para as instalações.   - - - Para cada um dos riscos identificados são - aconselhadas medidas preventivas e/ou - correctivas, de acordo com a legislação e - normativa vigente, tendo em vista a sua - eliminação, redução ou controlo para níveis - aceitáveis.   - - - ÍNDICE DAS TABELAS DE RISCO POR ÁREA DE - ACTIVIDADE - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9. PLANO DE ACTUAÇÃO   - - -   - - - A partir dos resultados da avaliação de riscos, - é elaborado um outro documento (Plano de - Actuação), que inclui a listagem das acções que - deverão ser realizadas de modo a eliminar, - reduzir ou controlar os riscos detectados.   - - - - Este Plano permitirá auxiliar a - - - - - - - - - - - na programação e acompanhamento das - referidas acções. - -   - - -   - - -   - - - 10. CONSIDERAÇÕES FINAIS - - -   - - - - A equipa técnica de Segurança e Higiene do - Trabalho da SIPRP agradece a colaboração de - todos os colaboradores da - - - - - - - - - - - durante a realização desta auditoria, - ficando à disposição para qualquer - esclarecimento. - -   - - -   - - -   - - -   - - - Lisboa, - - de - - de - - - -   - - - - - - - - - - - - - - - - - -   - - - - - - -   - - - Téc. Sup. Seg. Hig. do Trabalho -   - - - (CAP nº - - )   - - - - - - -   - - -   - - -   - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS LABORAIS   - - - - - - -   - - - - EMPRESA: - - - - - - - - - - -   - - - - ESTABELECIMENTO: - - - - - - - - - - - - DATA DA AVALIAÇÃO: - - - - de - - de - - -   - - - - - - AVALIAÇÃO: - - - - -   - - - - - - PRÓXIMA AVALIAÇÃO: - - - - de - - de - - -   - - - - - - - - REALIZADA POR: - - -  / SIPRP – - Sociedade Ibérica de Prevenção - de Riscos Profissionais   - - - - - - - - - POSTO DE TRABALHO: - - - - - - - - - - - - - - - - - - - - SEV.   - - - (S)   - - - - - PROB.   - - - (P)   - - - - - VALOR RISCO   - - - (S x P)   - - - - - RISCO / CONDIÇÕES ANÓMALAS /   - - - / ACÇÕES DE CONTROLO OU REDUÇÃO DO - RISCO   - - - - - - - - - -   - - - - -   - - - - -   - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - IRRELEVANTE - - - MUITO BAIXO - - - MUITO BAIXO - - - BAIXO - - - MÉDIO - - - ALTO - - - ALTO - - - MUITO ALTO - - - EXTREMAMENTE ALTO - - - - - - - - - - - -   - - - - -   - - - - - - - - - - -   - - - - - - - - - - - - - - - - . - - - ; - - - - - - - -   - - - - - - - - . - - - ; - - - - -   - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - Avaliação - - - - - - - de Riscos Laborais - - - - - - - - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2010-08-10.xsl b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2010-08-10.xsl deleted file mode 100644 index 25b5e155..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/relatorio_old_2010-08-10.xsl +++ /dev/null @@ -1,3009 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ATRIUM SALDANHA   - - - Praça Duque de Saldanha, 1 – 9º G   - - - 1050 – 094 Lisboa   - - - Telefone (+351) 213 504 540   - - - Fax (+351) 213 504 549   - - - geral@siprp.pt   - - - www.siprp.com   - - - - - Lisboa   - - - - - de - - - - - - - - - - AVALIAÇÃO DOS RISCOS PROFISSIONAIS   - - - Relatório - - -   - - -   - - -   - - - - - - - - -   - - -   - - - - - - - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - - - - - - - ÍNDICE - - - - - - - - - - - - 1. INTRODUÇÃO - - - - - - - 2. AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - 3. MEDIÇÃO DOS FACTORES DE RISCO - - - - - - - 4. LEGISLAÇÃO APLICÁVEL - - - - - - - 4.1 Legislação de aplicação geral - - - - - - - 4.2 Legislação específica - - - - - - - 5. NORMALIZAÇÃO APLICÁVEL - - - - - - - 6. EMPRESA CLIENTE - - - - - - - 7. TABELAS DE AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - 8. PLANO DE ACTUAÇÃO - - - - - - - 9. ACOMPANHAMENTO - - - - - - - 10. CONSIDERAÇÕES FINAIS - - - - - -   - - -   - - - - - - - - 1 - INTRODUÇÃO   - - - - - - - - - - - O empregador deve assegurar aos trabalhadores condições de segurança e saúde em todos os aspectos relacionados com o trabalho, aplicando as medidas necessárias tendo em conta os princípios gerais de prevenção. - - - - - Na aplicação das medidas de prevenção, o empregador deve mobilizar os meios necessários, nomeadamente nos domínios da prevenção técnica, da formação, informação e consulta dos trabalhadores e de serviços adequados, internos ou externos à empresa. - - - - - De acordo com a Lei nº 102/2009 de 10 de Setembro, que regulamenta o regime jurídico da promoção e prevenção da segurança e da saúde no trabalho, a prevenção dos riscos profissionais deve assentar numa correcta e permanente avaliação de riscos. - - - - - Enquanto entidade prestadora de serviços externos, a SIPRP - Sociedade Ibérica de Prevenção de Riscos Profissionais fomenta a implementação das medidas necessárias para prevenir os riscos profissionais e promover a segurança e a saúde dos trabalhadores, nomeadamente através da planificação da prevenção (integrando a todos os níveis a avaliação dos riscos e respectivas medidas de prevenção), da avaliação de riscos (com elaboração do respectivo relatório), da elaboração do plano de prevenção dos riscos profissionais e dos planos detalhados de prevenção e protecção (planos de actuação). - - - - - O presente documento reflecte a avaliação dos riscos profissionais realizada, assim como recomenda as respectivas medidas de prevenção necessárias. - - - - - Será igualmente emitido um outro documento no qual se elabora o plano de prevenção dos riscos profissionais, o qual é denominado de Plano de Actuação. - - - - - - - - - - - - - - 2 - AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - - - - - Uma avaliação dos riscos profissionais é um exame cuidadoso, realizado nos locais de trabalho, de forma a detectar os componentes aí existentes capazes de causar dano(s) ao(s) trabalhador(es) expostos. Na prática, trata-se de um processo dinâmico que reúne um duplo objectivo: - - - - - - - - - - • - - - - - Estimar a gravidade que um determinado risco no trabalho pode ter para a saúde e segurança dos trabalhadores, resultante das circunstâncias em que o perigo pode ocorrer; - - - - - - - • - - - - - Obter a informação necessária para que o empregador reúna condições para uma tomada de decisão apropriada, nomeadamente informação sobre a necessidade e o tipo de medidas preventivas a adoptar. - - - - - - - - A avaliação dos riscos profissionais constitui um processo dinâmico, uma vez que os riscos profissionais que a entidade patronal se vê obrigada a avaliar não ficam definitivamente determinados, mas vai evoluindo à medida que alterações se vão efectuando em função: - - - - - - - - - - • - - - - - do desenvolvimento progressivo das condições de trabalho; - - - - - - - - - - - • - - - - - das investigações científicas em matéria de riscos profissionais. - - - - - - - - A avaliação dos riscos profissionais deve ser eficiente e suficientemente detalhada para possibilitar uma adequada hierarquização dos riscos e consequente controlo. - - - - - Uma vez que assume uma linguagem mais objectiva, a SIPRP optou pelo método de matriz simples 4x4, que envolve a quantificação da probabilidade e da gravidade. - - - - - O método referido recorre a duas escalas de quatro níveis, para caracterizar as variáveis gravidade e probabilidade. - - - - - - - - - - - - Gravidade - - - - - - - - Probabilidade  - - - - - - - - Improvável   - - - 1   - - - - - Ocasional   - - - 2   - - - - - Provável   - - - 3   - - - - - Frequente   - - - 4   - - - - - - - Negligenciável - - - 1   - - - - - Aceitável   - - - 1   - - - - - Médio - - - 2   - - - - - Médio - - - 3   - - - - - Alto - - - 4   - - - - - - - Marginal - - - 2   - - - - - Médio - - - 2   - - - - - Médio   - - - 4   - - - - - Alto   - - - 6   - - - - - Muito alto   - - - 8   - - - - - - - Crítico - - - 3   - - - - - Médio - - - 3   - - - - - Alto   - - - 6   - - - - - Muito alto   - - - 9   - - - - - Extremamente alto - - - 12   - - - - - - - Catastrófico - - - 4   - - - - - Alto   - - - 4   - - - - - Muito alto   - - - 8   - - - - - Extremamente alto - - - 12   - - - - - Extremamente alto - - - 16   - - - - - - - Quadro – Matriz simples 4x4 - - - - - A interpretação do valor obtido pode ser realizada através da consulta do índice de risco, que traduz a prioridade de intervenção associada à avaliação feita. - - - - - - - - - - - Indice de risco - - - - - prioridade de intervenção - - - - - - - Aceitável - - - - - Actuação não prioritária - - - - - - - Médio - - - - - Intervenção a médio prazo - - - - - - - Alto - - - - - Intervenção a curto prazo - - - - - - - Muito alto - - - - - Actuação urgente - - - - - - - Extremamente alto - - - - - Actuação imediata - - - - - - - Quadro – Prioridade de intervenção de acordo com o índice de risco - - - Alguns riscos profissionais poderão ainda ser classificados como - indeterminados, dada a insuficência de informação. - - - - - - - - - - - - - - 3 - MEDIÇÃO DOS FACTORES DE RISCO - - - - - - - - - - - Uma vez que um dos princípios gerais de prevenção é assegurar que as exposições aos agentes químicos, físicos e biológicos e aos factores de risco psicossociais não constituem risco para a segurança e saúde do trabalhador nos locais de trabalho, a SIPRP, no decorrer das avaliações dos riscos profissionais, realiza medições aos seguintes parâmetros: - - - - - - - - - - • - - - - - Iluminância ou nível de iluminação; - - - - - - - • - - - - - Temperatura do ar; - - - - - - - • - - - - - Humidade relativa do ar; - - - - - - - • - - - - - Nível sonoro contínuo equivalente (ruído). - - - - - - - - Para realizar as referidas medições são utilizados os seguintes equipamentos: - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - Todos os equipamentos encontram-se devidamente calibrados por entidades acreditadas pelo Instituto Português de Acreditação. - - - - - - - - - - - - - - 4 - LEGISLAÇÃO APLICÁVEL - - - - - - - - - - - A avaliação dos riscos profissionais realizada pela SIPRP tem em conta as prescrições indicadas na legislação portuguesa em matéria de Segurança, Higiene e Saúde do Trabalho: - - - - - - - 4.1 Aplicação geral - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - 4.2 Aplicação específica - - - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - - - - - 5 - NORMALIZAÇÃO APLICÁVEL - - - - - - - - - - - Na realização da avaliação dos riscos profissionais é considerada além da legislação, também a normalização relativa à Segurança, Higiene e Saúde do Trabalho.  - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - • - - - - - - - - . - - - ; - - - - - - - - - - - - - - - - - - - - 6 - EMPRESA CLIENTE - - - - - - - - - - - A SIPRP realizou a avaliação dos riscos profissionais na empresa - , - estabelecimento de , - no dia - - de - - de - . - - - - - A actividade desenvolvida pela empresa é de . - - - - - De acordo com funções fornecidas, . - - - - - No decorrer da avaliação dos riscos profissionais, - a SIPRP obteve a colaboração e acompanhamento de - - ( - - ) - - e - ( - - ) - . - - - - - - - - - - - - - - 7 - TABELAS DE AVALIAÇÃO DOS RISCOS PROFISSIONAIS - - - - - - - - - - - A avaliação dos riscos profissionais realizada encontra-se nas tabelas que são apresentadas seguidamente. Nas mesmas são referidas igualmente as respectivas medidas de prevenção tidas como necessárias. - - - - - Os riscos comuns encontram-se agrupados por forma a facilitar a leitura do presente documento. - - - ÍNDICE DAS TABELAS DE RISCO POR ÁREA DE - ACTIVIDADE - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8 - PLANO DE ACTUAÇÃO - - - - - - - - - - - Após a avaliação dos riscos profissionais e da indicação das respectivas medidas de prevenção tidas como necessárias, a SIPRP emite um documento no qual é elaborado o plano de prevenção dos riscos profissionais, denominado de Plano de Actuação. - - - - - - - - - - - - - - 9 - ACOMPANHAMENTO - - - - - - - - - - - A SIPRP acompanha a execução das medidas de prevenção através de assessoramento ao cliente durante o preenchimento do Plano de Actuação. -   - - - - - A execução das medidas de prevenção são verificadas através da realização da avaliação dos riscos profissionais periódica. -   - - - - - - - - - - - - - - 10 - CONSIDERAÇÕES FINAIS - - - - - - - - - - - A SIPRP agradece a disponibilidade e o apoio de todos os colaboradores da empresa e fica ao dispor para qualquer esclarecimento. - - - - - - - - - Lisboa, - - de - - de - - - -   - - -  Realizado por: - - - - - - - - - - - - - - - - - - -   - - - - - - Técnico de Higiene e Segurança -   - - - CAP nº - - - - - - - - - - - -  Verificado por: - - - - - - - - - - - - - - - - - - -   - - - - - - Técnico Superior de Higiene e Segurança -   - - - CAP nº - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - AVALIAÇÃO DE RISCOS PROFISSIONAIS   - - - - - - -   - - - - EMPRESA: - - - - - - - - - - -   - - - - ESTABELECIMENTO: - - - - - - - - - - - - DATA DA AVALIAÇÃO: - - - - de - - de - - -   - - - - - - AVALIAÇÃO: - - - - -   - - - - - - PRÓXIMA AVALIAÇÃO: - - - - de - - de - - -   - - - - - - - - REALIZADA POR: - - - - - - - - - - / SIPRP – - Sociedade Ibérica de Prevenção - de Riscos Profissionais   - - - - - - - - - POSTO DE TRABALHO: - - - - - - - - - - - - - - - - - - - - GRAV.   - - - (G)   - - - - - PROB.   - - - (P)   - - - - - VALOR RISCO   - - - (G x P)   - - - - - RISCO / CONDIÇÕES ANÓMALAS /   - - - / ACÇÕES DE CONTROLO OU REDUÇÃO DO - RISCO   - - - - - - - - - -   - - - - -   - - - - -   - - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - - - - - - - - -   - - -   - - -   - - - - - - - - Aceitável - - - Médio - - - Médio - - - - - Médio - - - Alto - - - - - Alto - - - Muito alto - - - Muito alto - - - Extremamente alto - - - Extremamente alto - - - - - - - - - - - -   - - - - -   - - - - - - - - - - -   - - - - - - - - - - - - - - - - . - - - ; - - - - - - - -   - - - - - - - - . - - - ; - - - - -   - - - -   - - - - - - - - - - - - - - - - - - - - - - - - - Avaliação - - - - - - - dos Riscos Profissionais - - - - - - - - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input.xml b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input.xml deleted file mode 100644 index b4a8f8c5..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input.xml +++ /dev/null @@ -1,133 +0,0 @@ - - - - - COMPANHIA PORTUGUESA DE HIPERMERCADOS - - ALVERCA - - http://www.evolute.pt/~siprp/planoactuacao/siprp_logo.jpg - rua do estabelecimento - - - 2008 - 4 - Abril - 29 - - - 2008 - 3 - Março - 1 - - - Lei nº 99/2003 de 27 de Agosto regulamentada pela Lei - nº 35/2004 de 29 de Julho – Aprova o novo Código - de Trabalho - Decreto-Lei n.º441/91 de 14 de Novembro, alterado pelo - Decreto-Lei n.º133/99 de 21 de Abril – Estabelece o - regime jurídico do enquadramento da segurança, - higiene e saúde do trabalho - Decreto-Lei n.º26/94, de 1 de Fevereiro, alterado pela - Lei n.º7/95 de 29 de Março e pelo Decreto-Lei - n.º109/2000 – Regime de Organização e - funcionamento dos serviços da segurança, higiene e - saúde do trabalho - - - - Acidentes de Trabalho e Doenças Profissionais - - - - Lei nº 99/2003 de 27 de Agosto regulamentada pela - Lei nº 35/2004 de 29 de Julho – Aprova o novo - Código de Trabalho - - - Decreto-Lei n.º441/91 de 14 de Novembro, alterado - pelo Decreto-Lei n.º133/99 de 21 de Abril – - Estabelece o regime jurídico do enquadramento da - segurança, higiene e saúde do trabalho - - - Decreto-Lei n.º26/94, de 1 de Fevereiro, alterado - pela Lei n.º7/95 de 29 de Março e pelo - Decreto-Lei n.º109/2000 – Regime de - Organização e funcionamento dos serviços - da segurança, higiene e saúde do trabalho - - - - - - Área Administrativa - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - - Risco de exposição a condições - inadequadas de iluminação - - 6 - - - - Melhorar as condições de iluminação para valores - mínimos de 500 na área focal de trabalho e 300 - lux no seu envolvimento - - - Areas comerciais - - - - Cartazista - - - Frederico Palma - lampadas - - 2008 - 5 - Maio - 1 - - - 2009 - 5 - Maio - 1 - - OK - OK - OK - - - - Área Comercial - - - 1 - 2 - \ No newline at end of file diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input2.xml b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input2.xml deleted file mode 100644 index d305826b..00000000 --- a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/print/teste_input2.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - - COMPANHIA PORTUGUESA DE HIPERMERCADOS - - ALVERCA - http://apdp/siprp/auchan_jumbo_lado.jpg - rua do estabelecimento - - - 2008 - 4 - Abril - 29 - - - 2008 - 3 - Março - 1 - - - - Lei nº 99/2003 de 27 de Agosto regulamentada pela Lei - nº 35/2004 de 29 de Julho – Aprova o novo Código - de Trabalho - - - Decreto-Lei n.º441/91 de 14 de Novembro, alterado pelo - Decreto-Lei n.º133/99 de 21 de Abril – Estabelece o - regime jurídico do enquadramento da segurança, - higiene e saúde do trabalho - - - Decreto-Lei n.º26/94, de 1 de Fevereiro, alterado pela - Lei n.º7/95 de 29 de Março e pelo Decreto-Lei - n.º109/2000 – Regime de Organização e - funcionamento dos serviços da segurança, higiene e - saúde do trabalho - - - - - Acidentes de Trabalho e Doenças Profissionais - - - - Lei nº 99/2003 de 27 de Agosto regulamentada pela - Lei nº 35/2004 de 29 de Julho – Aprova o novo - Código de Trabalho - - - Decreto-Lei n.º441/91 de 14 de Novembro, alterado - pelo Decreto-Lei n.º133/99 de 21 de Abril – - Estabelece o regime jurídico do enquadramento da - segurança, higiene e saúde do trabalho - - - Decreto-Lei n.º26/94, de 1 de Fevereiro, alterado - pela Lei n.º7/95 de 29 de Março e pelo - Decreto-Lei n.º109/2000 – Regime de - Organização e funcionamento dos serviços - da segurança, higiene e saúde do trabalho - - - - - - Área Administrativa - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - Areas comerciais - - - - Risco de exposição a condições - inadequadas de iluminação - - 6 - - - - Melhorar as condições de iluminação para valores - mínimos de 500 na área focal de trabalho e 300 - lux no seu envolvimento - - - Areas comerciais - - - - Cartazista - - - Frederico Palma - lampadas - - 2008 - 5 - Maio - 1 - - - 2009 - 5 - Maio - 1 - - OK - OK - OK - - - - Área Comercial - - - 1 - 2 - \ No newline at end of file diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/revert.png b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/revert.png deleted file mode 100644 index f7e5f935..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/revert.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/submit.png b/trunk/SIPRPSoft/src/siprp/higiene/relatorio/submit.png deleted file mode 100644 index 7cb1f515..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/higiene/relatorio/submit.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/exames/logic/RecepcaoExamesLogic.java b/trunk/SIPRPSoft/src/siprp/medicina/exames/logic/RecepcaoExamesLogic.java deleted file mode 100644 index 695f0a80..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/exames/logic/RecepcaoExamesLogic.java +++ /dev/null @@ -1,76 +0,0 @@ -package siprp.medicina.exames.logic; - -import java.util.Collection; -import java.util.List; - -import leaf.ui.LeafDialog; -import leaf.ui.LeafLogic; -import shst.data.outer.PrestadoresData; -import shst.data.outer.TrabalhadoresEcdData; -import shst.data.provider.MedicinaDataProvider; - -import com.evolute.utils.error.ErrorLogger; - -public class RecepcaoExamesLogic extends LeafLogic -{ - - @Action(isSave = true) - public final static String ACTION_SELECT_ANALISADOR = "ACTION_SELECT_ANALISADOR"; - - @Action(isSave = false) - public final static String ACTION_SELECT_EXAME = "ACTION_SELECT_EXAME"; - - @Action(isSave = false) - public final static String ACTION_FILL_EXAMES = "ACTION_FILL_EXAMES"; - - @Action(isSave = true) - public final static String ACTION_RECEBER_EXAMES = "ACTION_RECEBER_EXAMES"; - - @Action(isSave = false) - public final static String ACTION_SORT = "ACTION_SORT"; - - public PrestadoresData currentAnalisador = null; - - private static MedicinaDataProvider dao = null; - static - { - try - { - dao = MedicinaDataProvider.getProvider(); - } - catch (Exception e) - { - ErrorLogger.logException( e ); - } - } - - @LeafLogicActionBinding(actions = ACTION_SELECT_ANALISADOR) - public void getExamesForAnalisador( PrestadoresData analisador ) - { - currentAnalisador = analisador; - if( analisador != null ) - { - Collection result = dao.getPendingExamesForAnalisador( currentAnalisador ); - runAction( ACTION_FILL_EXAMES, result ); - } - } - - @LeafLogicActionBinding(actions = ACTION_RECEBER_EXAMES) - public void receberExames( List ecds ) - { - try - { - if( ecds != null ) - { - for( TrabalhadoresEcdData ecd : ecds ) - { - ecd.save(); - } - } - } catch( Exception e ) - { - LeafDialog.error( e ); - } - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/exames/ui/RecepcaoExamesWindow.java b/trunk/SIPRPSoft/src/siprp/medicina/exames/ui/RecepcaoExamesWindow.java deleted file mode 100644 index 14d4aca7..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/exames/ui/RecepcaoExamesWindow.java +++ /dev/null @@ -1,235 +0,0 @@ -package siprp.medicina.exames.ui; - -import static com.evolute.utils.strings.UnicodeLatin1Map.atilde; -import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil; -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; - -import leaf.ui.LeafButton; -import leaf.ui.LeafInputField; -import leaf.ui.LeafTableModel; -import leaf.ui.LeafWindow; -import leaf.ui.LeafLogic.LeafUIActionBinding; -import shst.data.outer.EmpresasData; -import shst.data.outer.EstabelecimentosData; -import shst.data.outer.PrestadoresData; -import shst.data.outer.TrabalhadoresData; -import shst.data.outer.TrabalhadoresEcdData; -import shst.data.outer.TrabalhadoresEcdsData; -import shst.data.outer.TrabalhadoresEcdsDatasData; -import siprp.medicina.exames.logic.RecepcaoExamesLogic; - -import com.evolute.adt.OrderedMap; -import com.evolute.utils.tables.BaseTable; - -public class RecepcaoExamesWindow extends LeafWindow -{ - private static final long serialVersionUID = 1L; - - public static final String TITLE = "Recep" + ccedil + atilde + "o de ECDs"; - - private static final String TRABALHADOR = "Trabalhador"; - private static final String EMPRESA = "Empresa"; - - public final JLabel labelAnalisador = new JLabel( "Analisador" ); - - @ActionActivation(onSelect = RecepcaoExamesLogic.ACTION_SELECT_EXAME, onChange = "") - public BaseTable examesTable; - public LeafTableModel examesModel; - public JScrollPane examesScroll; - - @ActionActivation(onSelect = "", onChange = RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR) - public final LeafInputField> fieldAnalisador = new LeafInputField>(); - - public final JLabel labelData = new JLabel( "Data de recep" + ccedil + atilde + "o" ); - public final LeafInputField fieldData = new LeafInputField(); - - public final JLabel labelOrder = new JLabel("Ordenar por: "); - @ActionActivation(onSelect="", onChange=RecepcaoExamesLogic.ACTION_SORT) - public final LeafInputField> fieldOrder = new LeafInputField>(); - - @ActionActivation(onSelect=RecepcaoExamesLogic.ACTION_RECEBER_EXAMES, onChange="") - public final LeafButton buttonReceber = new LeafButton( "Receber" ); - - public final JPanel pane = new JPanel(); - - public RecepcaoExamesWindow() - { - super( new RecepcaoExamesLogic() ); - setTitle( TITLE ); - setupLayout(); - setupComponents(); - placeComponents(); - completeSetup(); - } - - private void setupLayout() - { - double[] cols = new double[] { - TableLayout.PREFERRED, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED - }; - double[] rows = new double[] { - TableLayout.PREFERRED, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED - }; - TableLayout layout = new TableLayout( cols, rows ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - pane.setLayout( layout ); - } - - private void setupComponents() - { - setContentPane( pane ); - examesModel = new LeafTableModel( new String[] { - "Empresa", "Estabelecimento", "Trabalhador", "Exame (tipo)", "Exame" - } ); - examesTable = new BaseTable( examesModel ); - examesTable.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); -// examesTable.setNonResizableNorReordable(); - examesTable.getTableHeader().setResizingAllowed( true ); - examesTable.getTableHeader().setReorderingAllowed( false ); - examesScroll = new JScrollPane( examesTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - - OrderedMap orderOptions = new OrderedMap(); - orderOptions.putLast( EMPRESA, EMPRESA ); - orderOptions.putLast( TRABALHADOR, TRABALHADOR ); - fieldOrder.setObject( orderOptions, EMPRESA ); - fieldOrder.setEditable( true ); - } - - private JPanel createMargin(boolean horizontal, int marginSize) - { - JPanel result = new JPanel(); - Dimension dim = new Dimension(horizontal ? 0 : marginSize, horizontal ? marginSize: 0 ); - result.setPreferredSize( dim ); - result.setSize( dim ); - return result; - } - - private void placeComponents() - { - pane.add( createMargin(true, 20), new TableLayoutConstraints(0,0,0,5)); - pane.add( createMargin(true, 20), new TableLayoutConstraints(7,0,7,5)); - pane.add( createMargin(false, 20), new TableLayoutConstraints(0,0,7,0)); - pane.add( createMargin(false, 20), new TableLayoutConstraints(0,5,7,5)); - pane.add( labelAnalisador, new TableLayoutConstraints( 1, 1, 2, 1 ) ); - pane.add( fieldAnalisador, new TableLayoutConstraints( 1, 2, 4, 2 ) ); - pane.add( labelData, new TableLayoutConstraints( 1, 3 ) ); - pane.add( fieldData, new TableLayoutConstraints( 1, 4, 2, 4 ) ); - pane.add( buttonReceber, new TableLayoutConstraints( 4, 4 ) ); - pane.add( examesScroll, new TableLayoutConstraints( 1, 5, 4, 5 ) ); - pane.add( labelOrder, new TableLayoutConstraints( 1, 6 ) ); - pane.add( fieldOrder, new TableLayoutConstraints( 2, 6, 3, 6 ) ); - } - - @LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_FILL_EXAMES) - public void fillExames(Collection exames) - { - examesTable.clearSelection(); - examesModel.clearAll(); - if(exames != null) - { - OrderedMap orderedMap = new OrderedMap(); - for( TrabalhadoresEcdData current : exames ) - { - TrabalhadoresEcdsDatasData exameMarcacao = current.toTrabalhadores_ecds_datas_id(); - EmpresasData empresa = null; - EstabelecimentosData estabelecimento = null; - TrabalhadoresData trabalhador = null; - TrabalhadoresEcdsData exame = null; - if( exameMarcacao != null ) - { - exame = exameMarcacao.toTrabalhadores_ecds_id(); - if( exame != null) - { - trabalhador = exame.toTrabalhador_id(); - if( trabalhador != null ) - { - estabelecimento = trabalhador.toEstabelecimento_id(); - if( estabelecimento != null ) - { - empresa = estabelecimento.toEmpresa_id(); - } - } - } - } - orderedMap.putLast( current, empresa, estabelecimento, trabalhador, current.toEcd_id().toGrupo_protocolo_id(), current ); - } - orderedMap.order( new int[]{ 0, 1, 2, 3, 4 } ); - examesModel.setValues( orderedMap ); - } - } - - @LeafUIActionBinding(action=RecepcaoExamesLogic.ACTION_SORT) - public void sort() - { - Object selected = fieldOrder.getSelectedObject(); - if( selected != null ) - { - if(selected.toString().equals( TRABALHADOR )) - { - examesModel.order( 2, 3, 4 ); - }else - { - examesModel.order( 0, 1, 2, 3, 4 ); - } - } - } - - @LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR) - public PrestadoresData selectAnalisador() - { - return (PrestadoresData)fieldAnalisador.getSelectedObject(); - } - - @LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_RECEBER_EXAMES) - public List receberExames() - { - List result = new ArrayList(); - int [] selectedRows = examesTable.getSelectedRows(); - if( selectedRows != null ) - { - for( int i = 0; i < selectedRows.length; ++i) - { - Object ecd = examesModel.getKey( selectedRows[i] ); - if(ecd != null) - { - if( ecd instanceof TrabalhadoresEcdData) - { - ((TrabalhadoresEcdData) ecd ).setData_recepcao( fieldData.getObject() ); - result.add( (TrabalhadoresEcdData) ecd ); - } - } - } - } - runActionLater( RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR ); - return result; - } - - @LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_STARTUP) - public void startup() - { - List prestadores = PrestadoresData.getAllPrestadores(); - PrestadoresData prestador = (prestadores == null || prestadores.size() == 0) ? null : prestadores.get( 0 ); - OrderedMap allPrestadores = new OrderedMap( prestadores ); - fieldAnalisador.setObject( allPrestadores, prestador ); - fieldAnalisador.setEditable( true ); - - fieldData.setObject( new Date() ); - fieldData.setEditable( true ); - - runActionLater( RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR ); - } - -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindow.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindow.java deleted file mode 100644 index cc61707e..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindow.java +++ /dev/null @@ -1,262 +0,0 @@ -package siprp.medicina.locais_analise; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.DateFormat; -import java.util.Date; -import java.util.Locale; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import javax.swing.WindowConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.data.IDObject; -import com.evolute.utils.dataui.ControllableComponent; -import com.evolute.utils.tracker.TrackableWindow; -import com.evolute.utils.ui.DialogException; -import com.evolute.utils.ui.calendar.JCalendarPanel; -import com.evolute.utils.ui.panel.CheckBoxPanel; - -public class EnviarAnalisesWindow extends SIPRPFrame - implements TrackableWindow, ActionListener, ChangeListener, ControllableComponent< Object > -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final String TITLE = "Enviar ECDs SIPRP para An\u00e1lise"; - - protected JCalendarPanel dataPanel; - protected JComboBox prestadorCombo; - protected JPanel ecdsOuterPanel; - protected CheckBoxPanel ecdsPanel; - protected JButton enviarButton; - - protected final EnviarAnalisesWindowLogic logic; - - public EnviarAnalisesWindow() - throws Exception - { - logic = new EnviarAnalisesWindowLogic( this ); - setupComponents(); - } - - private void setupComponents() - { - setTitle( TITLE ); - setSize( 500, 400 ); - - JLabel dataLabel = new JLabel( "Data" ); - dataPanel = new JCalendarPanel( this ); - dataPanel.addChangeListener( this ); - JLabel prestadorLabel = new JLabel( "Analisador" ); - prestadorCombo = new JComboBox(); - ecdsOuterPanel = new JPanel(); - ecdsOuterPanel.setLayout( new GridLayout( 1, 1 ) ); - enviarButton = new JButton( "Gravar" ); - enviarButton.addActionListener( this ); - - TableLayout layout = - new TableLayout( - new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.PREFERRED, - TableLayoutConstraints.MINIMUM, TableLayoutConstraints.PREFERRED }, - new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL, - TableLayoutConstraints.MINIMUM } ); - layout.setHGap( 2 ); - layout.setVGap( 2 ); - getContentPane().setLayout( layout ); - - getContentPane().add( dataLabel, new TableLayoutConstraints( 0, 0 ) ); - getContentPane().add( dataPanel, new TableLayoutConstraints( 1, 0 ) ); - getContentPane().add( prestadorLabel, new TableLayoutConstraints( 2, 0 ) ); - getContentPane().add( prestadorCombo, new TableLayoutConstraints( 3, 0 ) ); - getContentPane().add( ecdsOuterPanel, new TableLayoutConstraints( 0, 1, 3, 1 ) ); - getContentPane().add( enviarButton, new TableLayoutConstraints( 1, 2, 2, 2 ) ); - - - setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); - addWindowListener( new WindowAdapter(){ - public void windowClosing( WindowEvent e ) - { - close(); - } - - public void windowOpened( WindowEvent e ) - { -// setExtendedState( getExtendedState() | MAXIMIZED_BOTH ); - } - - } ); - dataPanel.setDate( new Date() ); - try - { - logic.dateChanged( dataPanel.getDate() ); - } - catch( Exception ex ) - { - if( dataPanel.getDate() != null ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar dados de " + DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) ).format( dataPanel.getDate() ), true ); - } - else - { - DialogException.showExceptionMessage( ex, "Erro a carregar dados de null", true ); - } - } - } - - public void refresh() - { - } - - public void open() - { - setVisible( true ); - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable() { - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - public boolean closeIfPossible() - { - close(); - return true; - } - - protected void setPrestadores( IDObject prestadores[] ) - { - prestadorCombo.removeAllItems(); - for( IDObject prestador : prestadores ) - { - prestadorCombo.addItem( prestador ); - } -// revalidate(); - } - - public void setEcds( IDObject ecds[] ) - { - ecdsPanel = new CheckBoxPanel( ecds ); - ecdsOuterPanel.removeAll(); - ecdsOuterPanel.add( ecdsPanel ); - revalidate(); - } - - @Override - public void actionPerformed( ActionEvent e ) - { - Object source = e.getSource(); - if( source.equals( enviarButton ) ) - { - try - { - logic.save(); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a gravar", true ); - } - } - } - - @Override - public void stateChanged( ChangeEvent e ) - { - Object source = e.getSource(); - if( source.equals( dataPanel ) ) - { - Date data = dataPanel.getDate(); - try - { - logic.dateChanged( data ); - } - catch( Exception ex ) - { - if( data != null ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar dados de " + DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) ).format( data ), true ); - } - else - { - DialogException.showExceptionMessage( ex, "Erro a carregar dados de null", true ); - } - } - } - } - - @Override - public void clear() - { - if( prestadorCombo.getItemCount() > 0 ) - { - prestadorCombo.setSelectedIndex( 0 ); - if( ecdsPanel != null ) - { - ecdsPanel.clear(); - } - } - } - - @Override - public void fill( Object value ) - { - clear(); - if( value != null ) - { - Date data = ( Date ) ( ( Object[] ) value )[ 0 ]; - Integer prestadorId = ( Integer ) ( ( Object[] ) value )[ 1 ]; - Integer ecdsEscolhidos[] = ( Integer[] ) ( ( Object[] ) value )[ 2 ]; - if( prestadorId == null ) - { - prestadorCombo.setSelectedIndex( 0 ); - } - else - { - for( int n = 0; n < prestadorCombo.getItemCount(); n++ ) - { - IDObject prestador = ( IDObject ) prestadorCombo.getItemAt( n ); - if( prestadorId.equals( prestador.getID() ) ) - { - prestadorCombo.setSelectedIndex( n ); - } - } - } - ecdsPanel.fill( ecdsEscolhidos ); - } - } - - @Override - public Object save() - { - return new Object[]{ - dataPanel.getDate(), - ( ( IDObject )prestadorCombo.getSelectedItem() ).getID(), - ecdsPanel != null ? ecdsPanel.save() : null }; - } - - private void revalidate() - { - ( ( JPanel ) getContentPane() ).revalidate(); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindowLogic.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindowLogic.java deleted file mode 100644 index 08becee8..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/EnviarAnalisesWindowLogic.java +++ /dev/null @@ -1,83 +0,0 @@ -package siprp.medicina.locais_analise; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Date; - -import shst.medicina.prestadores.PrestadoresDataProvider; -import siprp.medicina.locais_realizacao.LocaisRealizacaoConstants; -import siprp.medicina.locais_realizacao.LocaisRealizacaoDataProvider; - -import com.evolute.utils.data.IDObject; -import com.evolute.utils.ui.DialogException; - -class EnviarAnalisesWindowLogic -{ - protected final EnviarAnalisesWindow window; - protected final LocaisAnaliseLogic logic; - protected final PrestadoresDataProvider prestadoresProvider; - protected final LocaisRealizacaoDataProvider locaisRealizacaoProvider; - - public EnviarAnalisesWindowLogic( EnviarAnalisesWindow window ) - throws Exception - { - this.window = window; - logic = LocaisAnaliseLogic.getInstance(); - prestadoresProvider = PrestadoresDataProvider.getProvider(); - locaisRealizacaoProvider = LocaisRealizacaoDataProvider.getProvider(); - initWindow(); - } - - protected void initWindow() - throws Exception - { - window.addWindowListener( new WindowAdapter(){ - public void windowActivated( WindowEvent e ) - { - try - { - IDObject prestadores[] = prestadoresProvider.getPrestadoresActivos(); - IDObject prestadoresCompleto[] = - new IDObject[ prestadores.length + 1 ]; - prestadoresCompleto[ 0 ] = LocaisRealizacaoConstants.PRESTADOR_SIPRP; - for( int n = 0; n < prestadores.length; n++ ) - { - prestadoresCompleto[ n + 1 ] = prestadores[ n ]; - } - window.setPrestadores( prestadoresCompleto ); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar prestadores", true ); - } - } - } ); - } - - protected void dateChanged( Date data ) - throws Exception - { -System.out.println( "EnviarAnalisesWindowLogic.dateChanged: " + data ); - if( data != null ) - { - Integer idsMarcacoes[] = - locaisRealizacaoProvider.getMarcacoesEcdsIdsByDataAndPrestadorId( data, LocaisRealizacaoConstants.PRESTADOR_ID_SIPRP ); -System.out.println( "idsMarcacoes.length : " +idsMarcacoes.length ); - IDObject grupos[] = logic.getGruposEcdsByMarcacoes( idsMarcacoes ); - window.setEcds( grupos ); - window.fill( logic.getDataPrestadorEGruposByData( data ) ); - } - else - { - window.setEcds( new IDObject[ 0 ] ); - window.fill( null ); - } - } - - protected void save() - throws Exception - { - Object dados[] = ( Object[] ) window.save(); - logic.savePrestadorEGruposData( ( Date ) dados[ 0 ], ( Integer ) dados[ 1 ], ( Integer[] ) dados[ 2 ] ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseDataProvider.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseDataProvider.java deleted file mode 100644 index 00b7dce9..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseDataProvider.java +++ /dev/null @@ -1,138 +0,0 @@ -package siprp.medicina.locais_analise; - -import java.util.Date; - -import siprp.medicina.locais_realizacao.LocaisRealizacaoConstants; - -import com.evolute.utils.Singleton; -import com.evolute.utils.arrays.Virtual2DArray; -import com.evolute.utils.data.IDObject; -import com.evolute.utils.data.MappableObject; -import com.evolute.utils.db.DBManager; -import com.evolute.utils.db.Executer; -import com.evolute.utils.sql.Assignment; -import com.evolute.utils.sql.Begin; -import com.evolute.utils.sql.Commit; -import com.evolute.utils.sql.Delete; -import com.evolute.utils.sql.Expression; -import com.evolute.utils.sql.Field; -import com.evolute.utils.sql.Insert; -import com.evolute.utils.sql.Select; -import com.evolute.utils.sql.Select2; - -public class LocaisAnaliseDataProvider -{ - private static final Object LOCK = new Object(); - private static LocaisAnaliseDataProvider instance = null; - - private Executer EXECUTER; - - /** Creates a new instance of LocaisRealizacaoDataProvider */ - private LocaisAnaliseDataProvider() - throws Exception - { - DBManager dbm = ( DBManager ) Singleton.getInstance( Singleton.DEFAULT_DBMANAGER ); - EXECUTER = dbm.getSharedExecuter( this ); - } - - public static LocaisAnaliseDataProvider getProvider() - throws Exception - { - synchronized( LOCK ) - { - if( instance == null ) - { - instance = new LocaisAnaliseDataProvider(); - } - } - return instance; - } - - protected IDObject[] getGruposEcdsByMarcacoes( Integer marcacoesIds[] ) - throws Exception - { - if( marcacoesIds == null || marcacoesIds.length == 0 ) - { - return new IDObject[ 0 ]; - } - Select select = - new Select2( - new String[]{ "trabalhadores_ecd", "prt_tipos_elementos_protocolo", - "prt_grupos_protocolo"}, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_ecd.ecd_id" ).isEqual( - new Field( "prt_tipos_elementos_protocolo.id" ) ), - new Field( "prt_tipos_elementos_protocolo.grupo_protocolo_id" ).isEqual( - new Field( "prt_grupos_protocolo.id" ) ) - }, - new String[]{ "DISTINCT prt_grupos_protocolo.id", "prt_grupos_protocolo.descricao", - "prt_grupos_protocolo.ordem" }, - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).in( marcacoesIds ), - new String[]{ "prt_grupos_protocolo.ordem" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - IDObject grupos[] = new IDObject[ array.columnLength() ]; - for( int n = 0; n < grupos.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - grupos[ n ] = new MappableObject( id, descricao ); - } - return grupos; - } - - public void savePrestadorEGruposData( Date data, Integer prestadorId, Integer gruposIds[] ) - throws Exception - { - EXECUTER.executeQuery( Begin.BEGIN ); - Delete delete = - new Delete( "trabalhadores_ecds_analise", - new Field( "data" ).isEqual( data ) ); - EXECUTER.executeQuery( delete ); - if( prestadorId != null && !LocaisRealizacaoConstants.PRESTADOR_ID_SIPRP.equals( prestadorId ) - && gruposIds != null && gruposIds.length > 0 ) - { - Insert insert = - new Insert( "trabalhadores_ecds_analise", - new Assignment[]{ - new Assignment( new Field( "data" ), data ), - new Assignment( new Field( "prestador_id" ), prestadorId ), - new Assignment( new Field( "grupo_ecds_id" ), gruposIds ) - } ); - EXECUTER.executeQuery( insert ); - } - EXECUTER.executeQuery( Commit.COMMIT ); - } - - public Object[] getDataPrestadorEGruposByData( Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "trabalhadores_ecds_analise" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "prestador_id", "grupo_ecds_id" }, - new Field( "data" ).isEqual( data ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - if( array.columnLength() == 0 ) - { - return null; - } - Integer grupos[] = new Integer[ array.columnLength() ]; - for( int n = 0; n < grupos.length; n++ ) - { - grupos[ n ] = ( Integer ) array.get( n, 1 ); - } - return new Object[]{ data, array.get( 0, 0 ), grupos }; - } -} - - \ No newline at end of file diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseLogic.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseLogic.java deleted file mode 100644 index eb4ed982..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/LocaisAnaliseLogic.java +++ /dev/null @@ -1,50 +0,0 @@ -package siprp.medicina.locais_analise; - -import java.util.Date; - -import com.evolute.utils.data.IDObject; - -public final class LocaisAnaliseLogic -{ - private static final Object LOCK = new Object(); - private static LocaisAnaliseLogic instance; - - private final LocaisAnaliseDataProvider provider; - - private LocaisAnaliseLogic() - throws Exception - { - provider = LocaisAnaliseDataProvider.getProvider(); - } - - public static LocaisAnaliseLogic getInstance() - throws Exception - { - synchronized( LOCK ) - { - if( instance == null ) - { - instance = new LocaisAnaliseLogic(); - } - } - return instance; - } - - protected IDObject[] getGruposEcdsByMarcacoes( Integer marcacoesIds[] ) - throws Exception - { - return provider.getGruposEcdsByMarcacoes( marcacoesIds ); - } - - protected void savePrestadorEGruposData( Date data, Integer prestadorId, Integer gruposIds[] ) - throws Exception - { - provider.savePrestadorEGruposData( data, prestadorId, gruposIds ); - } - - protected Object[] getDataPrestadorEGruposByData( Date data ) - throws Exception - { - return provider.getDataPrestadorEGruposByData( data ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/ReceberAnalisesWindow.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/ReceberAnalisesWindow.java deleted file mode 100644 index c71b0704..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_analise/ReceberAnalisesWindow.java +++ /dev/null @@ -1,6 +0,0 @@ -package siprp.medicina.locais_analise; - -public class ReceberAnalisesWindow -{ - -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/FaxPrinter.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/FaxPrinter.java deleted file mode 100644 index e6ba4b5c..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/FaxPrinter.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * FaxPrinter.java - * - * Created on March 1, 2007, 3:26 PM - * - * To change this template, choose Tools | Template Manager - * and open the template in the editor. - */ - -package siprp.medicina.locais_realizacao; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.SwingUtilities; - -import com.evolute.utils.data.IDObject; -import com.evolute.utils.data.MappableObject; -import com.evolute.utils.ui.CustomJDialog; -import com.evolute.utils.ui.panel.CheckBoxPanel; - -/** - * - * @author fpalma - */ -public class FaxPrinter extends CustomJDialog - implements ActionListener -{ - private JTextField deText; - private JTextField deEmailText; - private JTextField deFaxText; - private JTextField deTelefoneText; - private JTextField assuntoText; - private JTextField localText; - private JToggleButton localAutoButton; - private JTextField perfil1Text; - private CheckBoxPanel perfil1Panel; - private JTextField perfil2Text; - private CheckBoxPanel perfil2Panel; - private JTextField horaText; - - private JButton imprimirButton; - private JButton cancelarButton; - - public static void main( String args[] ) - { - FaxPrinter d = new FaxPrinter(); - d.setVisible( true ); - } - - /** Creates a new instance of FaxPrinter */ - public FaxPrinter() - { - super( null, true ); - setupComponents(); - } - - private void setupComponents() - { - setTitle( "Por favor preencha os detalhes do Fax" ); - setSize( 800, 600 ); - - JLabel deLabel = new JLabel( "De" ); - deText = new JTextField(); - JLabel deEmailLabel = new JLabel( "E-mail" ); - deEmailText = new JTextField(); - JLabel deFaxLabel = new JLabel( "Fax" ); - deFaxText = new JTextField(); - JLabel deTelefoneLabel = new JLabel( "N\u00famero de telefone" ); - deTelefoneText = new JTextField(); - JLabel assuntoLabel = new JLabel( "Assunto" ); - assuntoText = new JTextField(); - localAutoButton = new JToggleButton( "Local Autom\u00e1tico" ); - localText = new JTextField(); - JLabel perfil1Label = new JLabel( "Nome" ); - perfil1Text = new JTextField(); - perfil1Panel = new CheckBoxPanel( new IDObject[]{ new MappableObject( new Integer( 1 ), "teste1" ), - new MappableObject( new Integer( 3 ), "teste3" ) } ); - JLabel perfil2Label = new JLabel( "Nome" ); - perfil2Text = new JTextField(); - perfil2Panel = new CheckBoxPanel( new IDObject[]{ new MappableObject( new Integer( 2 ), "teste2" ) } ); - imprimirButton = new JButton( "Imprimir" ); - imprimirButton.addActionListener( this ); - cancelarButton = new JButton( "Cancelar" ); - cancelarButton.addActionListener( this ); - JPanel buttonPanel = new JPanel(); - JPanel perfil1OuterPanel = new JPanel(); - perfil1OuterPanel.setBorder( BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), "Perfil 1" ) ); - JPanel perfil2OuterPanel = new JPanel(); - perfil2OuterPanel.setBorder( BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), "Perfil 2" ) ); - - double cols[] = - new double[]{ TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, - TableLayout.FILL, }; - double rows[] = - new double[]{ TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, - TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED }; - - TableLayout tableLayout = new TableLayout( cols,rows ); - setLayout( tableLayout ); - - add( deLabel, new TableLayoutConstraints( 0, 0 ) ); - add( deText, new TableLayoutConstraints( 1, 0 ) ); - add( deEmailLabel, new TableLayoutConstraints( 2, 0 ) ); - add( deEmailText, new TableLayoutConstraints( 3, 0 ) ); - add( deFaxLabel, new TableLayoutConstraints( 0, 1 ) ); - add( deFaxText, new TableLayoutConstraints( 1, 1 ) ); - add( deTelefoneLabel, new TableLayoutConstraints( 2, 1 ) ); - add( deTelefoneText, new TableLayoutConstraints( 3, 1 ) ); - add( assuntoLabel, new TableLayoutConstraints( 0, 2 ) ); - add( assuntoText, new TableLayoutConstraints( 1, 2, 3, 2 ) ); - add( localAutoButton, new TableLayoutConstraints( 0, 3 ) ); - add( localText, new TableLayoutConstraints( 1, 3, 3, 3 ) ); - add( perfil1OuterPanel, new TableLayoutConstraints( 0, 4, 1, 4 ) ); - add( perfil2OuterPanel, new TableLayoutConstraints( 2, 4, 3, 4 ) ); - add( buttonPanel, new TableLayoutConstraints( 0, 5, 3, 5 ) ); - - cols = new double[]{ TableLayout.MINIMUM, TableLayout.FILL }; - rows = new double[]{ TableLayout.PREFERRED, TableLayout.FILL }; - - tableLayout = new TableLayout( cols,rows ); - perfil1OuterPanel.setLayout( tableLayout ); - - perfil1OuterPanel.add( perfil1Label, new TableLayoutConstraints( 0, 0 ) ); - perfil1OuterPanel.add( perfil1Text, new TableLayoutConstraints( 1, 0 ) ); - perfil1OuterPanel.add( perfil1Panel, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - - tableLayout = new TableLayout( cols,rows ); - perfil2OuterPanel.setLayout( tableLayout ); - - perfil2OuterPanel.add( perfil2Label, new TableLayoutConstraints( 0, 0 ) ); - perfil2OuterPanel.add( perfil2Text, new TableLayoutConstraints( 1, 0 ) ); - perfil2OuterPanel.add( perfil2Panel, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - - buttonPanel.setLayout( new FlowLayout( FlowLayout.CENTER ) ); - buttonPanel.add( imprimirButton ); - buttonPanel.add( cancelarButton ); - - } - - public void actionPerformed(ActionEvent e) - { - Object source = e.getSource(); - if( source.equals( imprimirButton ) ) - { - print(); - } - else if( source.equals( cancelarButton ) ) - { - close(); - } - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable(){ - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - public void print() - { - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoConstants.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoConstants.java deleted file mode 100644 index 1911b738..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoConstants.java +++ /dev/null @@ -1,11 +0,0 @@ -package siprp.medicina.locais_realizacao; - -import com.evolute.utils.data.IDObject; -import com.evolute.utils.data.MappableObject; - -public class LocaisRealizacaoConstants -{ - public static final Integer PRESTADOR_ID_SIPRP = new Integer( -1 ); - - public static final IDObject PRESTADOR_SIPRP = new MappableObject( PRESTADOR_ID_SIPRP, "SIPRP" ); -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoDataProvider.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoDataProvider.java deleted file mode 100644 index b7a80564..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoDataProvider.java +++ /dev/null @@ -1,530 +0,0 @@ -/* - * LocaisRealizacaoDataProvider.java - * - * Created on February 22, 2007, 10:44 AM - * - * To change this template, choose Tools | Template Manager - * and open the template in the editor. - */ - -package siprp.medicina.locais_realizacao; - -import java.util.Date; - -import shst.MedicinaConstants; - -import com.evolute.utils.Singleton; -import com.evolute.utils.arrays.Virtual2DArray; -import com.evolute.utils.data.IDObject; -import com.evolute.utils.data.MappableObject; -import com.evolute.utils.db.DBManager; -import com.evolute.utils.db.Executer; -import com.evolute.utils.sql.Assignment; -import com.evolute.utils.sql.Expression; -import com.evolute.utils.sql.Field; -import com.evolute.utils.sql.Select; -import com.evolute.utils.sql.Select2; -import com.evolute.utils.sql.Union; -import com.evolute.utils.sql.Update; -import com.evolute.utils.tables.ColumnizedMappable; - -/** - * - * @author fpalma - */ -public class LocaisRealizacaoDataProvider -{ - private static final Object LOCK = new Object(); - private static LocaisRealizacaoDataProvider instance = null; - - private Executer EXECUTER; - - /** Creates a new instance of LocaisRealizacaoDataProvider */ - private LocaisRealizacaoDataProvider() - throws Exception - { - DBManager dbm = ( DBManager ) Singleton.getInstance( Singleton.DEFAULT_DBMANAGER ); - EXECUTER = dbm.getSharedExecuter( this ); - } - - public static LocaisRealizacaoDataProvider getProvider() - throws Exception - { - synchronized( LOCK ) - { - if( instance == null ) - { - instance = new LocaisRealizacaoDataProvider(); - } - } - return instance; - } - - public ColumnizedMappable[] getEmpresasComMarcacoes( Date data ) - throws Exception - { - - - Select selectConsultas = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores", "estabelecimentos" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ), - new Field( "trabalhadores.estabelecimento_id" ).isEqual( new Field( "estabelecimentos.id" ) ) }, - new String[]{ "estabelecimentos.empresa_id" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Select selectEcds = - new Select2( - new String[]{ "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores", "estabelecimentos" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ), - new Field( "trabalhadores.estabelecimento_id" ).isEqual( new Field( "estabelecimentos.id" ) ) }, - new String[]{ "estabelecimentos.empresa_id" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - - Select select = - new Select2( - new String[]{ "empresas" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "DISTINCT empresas.id", "empresas.designacao_social", "empresas.designacao_social_plain" }, - new Field( "empresas.id" ).in( new Union( new Select[]{ selectConsultas, selectEcds }, new int[]{} ) ), - new String[]{ "empresas.designacao_social_plain" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - ColumnizedMappable empresas[] = new ColumnizedMappable[ array.columnLength() ]; - for( int n = 0; n < empresas.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String designacao = ( String ) array.get( n, 1 ); - empresas[ n ] = new ColumnizedMappable( id, designacao ); - } - return empresas; - } - - public ColumnizedMappable[] getEstabelecimentosComMarcacoesByEmpresa( Integer empresaID, Date data ) - throws Exception - { - Select selectConsultas = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "trabalhadores.estabelecimento_id" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Select selectEcds = - new Select2( - new String[]{ "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "trabalhadores.estabelecimento_id" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - - Select select = - new Select2( - new String[]{ "estabelecimentos" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "DISTINCT estabelecimentos.id", "estabelecimentos.nome", "estabelecimentos.nome_plain" }, - new Field( "estabelecimentos.id" ).in( new Union( new Select[]{ selectConsultas, selectEcds }, new int[]{} ) ).and( - new Field( "estabelecimentos.inactivo" ).isEqual( "n" ) ).and( - new Field( "empresa_id" ).isEqual( empresaID ) ), - new String[]{ "estabelecimentos.nome_plain" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - ColumnizedMappable estabelecimentos[] = new ColumnizedMappable[ array.columnLength() ]; - for( int n = 0; n < estabelecimentos.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String nome = ( String ) array.get( n, 1 ); - estabelecimentos[ n ] = new ColumnizedMappable( id, nome ); - } - - return estabelecimentos; - } - - public int getNumeroConsultasByEstabelecimentoAndDate( Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "COUNT( DISTINCT trabalhadores.id )" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - return ( ( Number ) array.get( 0, 0 ) ).intValue(); - } - - public Integer[] getPrestadoresConsultaIdByEstabelecimentoAndDate( Integer estabelecimentoId, Date data ) - throws Exception - { - Select selectExterno = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_consultas_datas.prestador_id" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray arrayExterno = EXECUTER.executeQuery( selectExterno ); - Integer ids[] = new Integer[ arrayExterno.columnLength() ]; - for( int n = 0; n < arrayExterno.columnLength(); n++ ) - { - ids[ n ] = ( Integer ) arrayExterno.get( n, 0 ); - } - return ids; - } - - public void setPrestadorConsultaIdForEstabelecimentoAndDate( Integer estabelecimentoId, Date data, Integer prestadorId ) - throws Exception - { - Select selectConsultas = - new Select2( - new String[]{ "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_consultas.id" }, - new Field( "trabalhadores_consultas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Update updateConsultas = new Update( "trabalhadores_consultas", - new Assignment[]{ - new Assignment( new Field( "prestador_id" ), prestadorId ) - }, - new Field( "id" ).in( selectConsultas ) ); - EXECUTER.executeQuery( updateConsultas ); - - Select selectConsultasDatas = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_consultas_datas.id" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Update updateConsultasDatas = new Update( "trabalhadores_consultas_datas", - new Assignment[]{ - new Assignment( new Field( "prestador_id" ), prestadorId ) - }, - new Field( "id" ).in( selectConsultasDatas ) ); - EXECUTER.executeQuery( updateConsultasDatas ); - } - - protected IDObject[] getGruposEcdsByEstabelecimentoAndDate( Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "prt_grupos_protocolo", "prt_tipos_elementos_protocolo", "trabalhadores_ecd", - "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "prt_grupos_protocolo.id" ).isEqual( new Field( "prt_tipos_elementos_protocolo.grupo_protocolo_id" ) ), - new Field( "prt_tipos_elementos_protocolo.id" ).isEqual( new Field( "trabalhadores_ecd.ecd_id" ) ), - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT prt_grupos_protocolo.id", "prt_grupos_protocolo.descricao", "prt_grupos_protocolo.ordem", - "prt_grupos_protocolo.descricao_plain" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - new String[]{ "prt_grupos_protocolo.ordem", "prt_grupos_protocolo.descricao_plain" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - IDObject grupos[] = new IDObject[ array.columnLength() ]; - for( int n = 0; n < grupos.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - grupos[ n ] = new MappableObject( id, descricao ); - } - return grupos; - } - - public Integer[] getPrestadoresByGrupoEcdEstabelecimentoAndDate( Integer grupoId, Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "prt_tipos_elementos_protocolo", "trabalhadores_ecd", - "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "prt_tipos_elementos_protocolo.id" ).isEqual( new Field( "trabalhadores_ecd.ecd_id" ) ), - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_ecds_datas.prestador_id" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "prt_tipos_elementos_protocolo.grupo_protocolo_id" ).isEqual( grupoId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Integer prestadores[] = new Integer[ array.columnLength() ]; - for( int n = 0; n < prestadores.length; n++ ) - { - prestadores[ n ] = ( Integer ) array.get( n, 0 ); - } - return prestadores; - } - - public int getNumeroMarcacoesByGrupoEcdEstabelecimentoAndDate( Integer grupoId, Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "prt_tipos_elementos_protocolo", "trabalhadores_ecd", - "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "prt_tipos_elementos_protocolo.id" ).isEqual( new Field( "trabalhadores_ecd.ecd_id" ) ), - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "COUNT( DISTINCT trabalhadores.id)" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "prt_tipos_elementos_protocolo.grupo_protocolo_id" ).isEqual( grupoId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - return ( ( Number ) array.get( 0, 0 ) ).intValue(); - } - - public void setPrestadorIdForGruposEcdsEstabelecimentoAndDate( Integer estabelecimentoId, Date data, Integer prestadorId ) - throws Exception - { - Select selectConsultas = - new Select2( - new String[]{ "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_consultas.id" }, - new Field( "trabalhadores_consultas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Update updateConsultas = new Update( "trabalhadores_consultas", - new Assignment[]{ - new Assignment( new Field( "prestador_id" ), prestadorId ) - }, - new Field( "id" ).in( selectConsultas ) ); - EXECUTER.executeQuery( updateConsultas ); - - Select selectConsultasDatas = - new Select2( - new String[]{ "trabalhadores_consultas_datas", "trabalhadores_consultas", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_consultas_datas.trabalhadores_consultas_id" ).isEqual( new Field( "trabalhadores_consultas.id" ) ), - new Field( "trabalhadores_consultas.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_consultas_datas.id" }, - new Field( "trabalhadores_consultas_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_consultas_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Update updateConsultasDatas = new Update( "trabalhadores_consultas_datas", - new Assignment[]{ - new Assignment( new Field( "prestador_id" ), prestadorId ) - }, - new Field( "id" ).in( selectConsultasDatas ) ); - EXECUTER.executeQuery( updateConsultasDatas ); - } - - protected IDObject[] getExamesOficiaisByEstabelecimentoAndDate( Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "ecd_oficial", "trabalhadores_ecd", - "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "ecd_oficial.id" ).isEqual( new Field( "trabalhadores_ecd.ecd_oficial_id" ) ), - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT ecd_oficial.id", "ecd_oficial.descricao", "ecd_oficial.ordem", - "ecd_oficial.descricao_plain" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - new String[]{ "ecd_oficial.ordem", "ecd_oficial.descricao_plain" }, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - IDObject ecds[] = new IDObject[ array.columnLength() ]; - for( int n = 0; n < ecds.length; n++ ) - { - Integer id = ( Integer ) array.get( n, 0 ); - String descricao = ( String ) array.get( n, 1 ); - ecds[ n ] = new MappableObject( id, descricao ); - } - return ecds; - } - - public Integer[] getPrestadoresByEcdOficialEstabelecimentoAndDate( Integer ecdOficialId, Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "trabalhadores_ecd", "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "DISTINCT trabalhadores_ecds_datas.prestador_id" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_ecd.ecd_oficial_id" ).isEqual( ecdOficialId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Integer prestadores[] = new Integer[ array.columnLength() ]; - for( int n = 0; n < prestadores.length; n++ ) - { - prestadores[ n ] = ( Integer ) array.get( n, 0 ); - } - return prestadores; - } - - public int getNumeroMarcacaoesByEcdOficialEstabelecimentoAndDate( Integer ecdOficialId, Integer estabelecimentoId, Date data ) - throws Exception - { - Select select = - new Select2( - new String[]{ "trabalhadores_ecd", "trabalhadores_ecds_datas", "trabalhadores_ecds", "trabalhadores" }, - new Integer[]{ Select2.JOIN_INNER, Select2.JOIN_INNER, Select2.JOIN_INNER }, - new Expression[]{ - new Field( "trabalhadores_ecd.trabalhadores_ecds_datas_id" ).isEqual( new Field( "trabalhadores_ecds_datas.id" ) ), - new Field( "trabalhadores_ecds_datas.trabalhadores_ecds_id" ).isEqual( new Field( "trabalhadores_ecds.id" ) ), - new Field( "trabalhadores_ecds.trabalhador_id" ).isEqual( new Field( "trabalhadores.id" ) ) }, - new String[]{ "COUNT( DISTINCT trabalhadores.id)" }, - new Field( "trabalhadores_ecds_datas.data" ).isEqual( data ).and( - new Field( "trabalhadores.estabelecimento_id" ).isEqual( estabelecimentoId ) ).and( - new Field( "trabalhadores_ecd.ecd_oficial_id" ).isEqual( ecdOficialId ) ).and( - new Field( "trabalhadores_ecds_datas.estado" ).isEqual( new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ) ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - return ( ( Number ) array.get( 0, 0 ) ).intValue(); - } - - public Integer []getMarcacoesEcdsIdsByDataAndPrestadorId( Date data, Integer prestadorId ) - throws Exception - { - if( LocaisRealizacaoConstants.PRESTADOR_ID_SIPRP.equals( prestadorId ) ) - { - prestadorId = null; - } - Select select = - new Select2( - new String[]{ "trabalhadores_ecds_datas" }, - new Integer[]{}, - new Expression[]{}, - new String[]{ "id" }, - new Field( "data" ).isEqual( data ).and( - new Field("prestador_id" ).isEqual( prestadorId ) ).and( - new Field( "estado" ).in( - new Integer[]{ - new Integer( MedicinaConstants.ESTADO_POR_REALIZAR ), - new Integer( MedicinaConstants.ESTADO_PARCIALMENTE_REALIZADO ), - new Integer( MedicinaConstants.ESTADO_REALIZADO ) } ) ), - null, - null, - null, - null ); - Virtual2DArray array = EXECUTER.executeQuery( select ); - Integer ids[] = new Integer[ array.columnLength() ]; - for( int n = 0; n < array.columnLength(); n++ ) - { - ids[ n ] = ( Integer ) array.get( n, 0 ); - } - return ids; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoWindow.java b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoWindow.java deleted file mode 100644 index cbf427bb..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/LocaisRealizacaoWindow.java +++ /dev/null @@ -1,730 +0,0 @@ -/* - * LocaisRealizacaoWindow.java - * - * Created on February 22, 2007, 10:19 AM - * - * To change this template, choose Tools | Template Manager - * and open the template in the editor. - */ - -package siprp.medicina.locais_realizacao; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.Color; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Arrays; -import java.util.Date; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.WindowConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import shst.medicina.prestadores.PrestadoresDataProvider; -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.data.IDObject; -import com.evolute.utils.tables.BaseTable; -import com.evolute.utils.tables.ColumnizedMappable; -import com.evolute.utils.tables.VectorTableModel; -import com.evolute.utils.tracker.TrackableWindow; -import com.evolute.utils.ui.DialogException; -import com.evolute.utils.ui.calendar.JCalendarPanel; - -/** - * - * @author fpalma - */ -public class LocaisRealizacaoWindow extends SIPRPFrame - implements ActionListener, TrackableWindow, ListSelectionListener -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - protected JCalendarPanel dataPanel; - protected JButton carregarButton; -// protected JButton recarregarPrestadoresButton; - protected VectorTableModel empresasModel; - protected BaseTable empresasTable; - protected VectorTableModel estabelecimentosModel; - protected BaseTable estabelecimentosTable; - protected JLabel numeroConsultasLabel; - protected JComboBox prestadoresConsultasCombo; - protected JButton enviarConsultasButton; - protected JButton faxConsultasButton; - protected JButton enviarECDsButton; - protected JScrollPane listaEcdsScroll; - -// protected JLabel numeroECDsLabel; - protected Integer idsGruposEcds[]; - protected JComboBox prestadoresECDsCombos[]; - protected Integer idsEcdsOficiais[]; - protected JComboBox prestadoresECDsOficiaisCombos[]; -// protected JButton faxECDsButton; - - protected LocaisRealizacaoDataProvider provider; - protected PrestadoresDataProvider prestadoresProvider; - - /** - * Creates a new instance of LocaisRealizacaoWindow - */ - public LocaisRealizacaoWindow() - throws Exception - { - provider = LocaisRealizacaoDataProvider.getProvider(); - prestadoresProvider = PrestadoresDataProvider.getProvider(); - setupComponents(); - } - - private void setupComponents() - { - setTitle( "Locais de Realiza\u00e7\u00e3o" ); - setSize( 1000, 700 ); - JLabel dataLabel = new JLabel( "Data" ); - dataPanel = new JCalendarPanel( this ); - - carregarButton = new JButton( "Carregar" ); - carregarButton.addActionListener( this ); -// recarregarPrestadoresButton = new JButton( "Recarregar Prestadores" ); -// recarregarPrestadoresButton.addActionListener( this ); - empresasModel = new VectorTableModel( new String[]{ "empresa" } ); - empresasTable = new BaseTable( empresasModel ); - empresasTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - empresasTable.getSelectionModel().addListSelectionListener( this ); - JScrollPane empresasScp = new JScrollPane( empresasTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - estabelecimentosModel = new VectorTableModel( new String[]{ "estabelecimento" } ); - estabelecimentosTable = new BaseTable( estabelecimentosModel ); - estabelecimentosTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); - estabelecimentosTable.getSelectionModel().addListSelectionListener( this ); - JScrollPane estabelecimentosScp = new JScrollPane( estabelecimentosTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ); - JPanel consultasPanel = new JPanel(); - consultasPanel.setBorder( BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), "Consultas" ) ); - JLabel consultasLabel = new JLabel( "N\u00ba de Consultas: " ); - numeroConsultasLabel = new JLabel( " " ); - numeroConsultasLabel.setForeground( Color.green.darker() ); - prestadoresConsultasCombo = new JComboBox(); - enviarConsultasButton = new JButton( "Atribuir" ); - enviarConsultasButton.addActionListener( this ); - faxConsultasButton = new JButton( "Fax" ); - faxConsultasButton.addActionListener( this ); - JPanel ecdsPanel = new JPanel(); - ecdsPanel.setBorder( BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), "ECDs" ) ); -// JLabel ecdsLabel = new JLabel( "Quantidade " ); -// numeroECDsLabel = new JLabel( " " ); -// numeroECDsLabel.setForeground( Color.green.darker() ); -// prestadoresECDsCombo = new JComboBox(); - listaEcdsScroll = new JScrollPane(); - listaEcdsScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ); - listaEcdsScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); - enviarECDsButton = new JButton( "Atribuir" ); - enviarECDsButton.addActionListener( this ); -// faxECDsButton = new JButton( "Fax" ); -// faxECDsButton.addActionListener( this ); - dataPanel.addChangeListener( new ChangeListener(){ - public void stateChanged(ChangeEvent e) - { - empresasTable.clearSelection(); - Vector values = empresasModel.getValues(); - values.clear(); - empresasModel.setValues( values ); - } - } ); - - TableLayout layout = - new TableLayout( - new double[]{ TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL }, - new double[]{ TableLayout.MINIMUM, TableLayout.FILL, TableLayout.FILL } ); - layout.setHGap( 5 ); - layout.setVGap( 5 ); - -// getContentPane().setLayout( new BorderLayout( 5, 5 ) ); - getContentPane().setLayout( layout ); - JPanel upperPanel = new JPanel(); - getContentPane().add( upperPanel, new TableLayoutConstraints( 0, 0, 3, 0 ) ); - getContentPane().add( empresasScp, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - getContentPane().add( estabelecimentosScp, new TableLayoutConstraints( 2, 1, 3, 1 ) ); -// JPanel detalhesPanel = new JPanel(); -// getContentPane().add( detalhesPanel, new TableLayoutConstraints( 0, 2, 1, 2 ) ); - getContentPane().add( consultasPanel, new TableLayoutConstraints( 0, 2 ) ); - getContentPane().add( ecdsPanel, new TableLayoutConstraints( 1, 2, 3, 2 ) ); -// getContentPane().add( upperPanel, BorderLayout.NORTH ); -// JPanel centerPanel = new JPanel(); -// getContentPane().add( centerPanel, BorderLayout.CENTER ); - - upperPanel.setLayout( new FlowLayout( FlowLayout.CENTER ) ); - upperPanel.add( dataLabel ); - upperPanel.add( dataPanel ); - upperPanel.add( carregarButton ); -// upperPanel.add( recarregarPrestadoresButton ); - -// centerPanel.setLayout( new GridLayout( 1, 3 ) ); -// centerPanel.add( empresasScp ); -// centerPanel.add( estabelecimentosScp ); -// JPanel detalhesPanel = new JPanel(); -// centerPanel.add( detalhesPanel ); - - double cols[] = - new double[]{ TableLayout.MINIMUM, TableLayout.FILL }; - double rows[] = - new double[]{ TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM }; - - TableLayout tableLayout = new TableLayout( cols,rows ); - consultasPanel.setLayout( tableLayout ); - - consultasPanel.add( consultasLabel, new TableLayoutConstraints( 0, 0 ) ); - consultasPanel.add( numeroConsultasLabel, new TableLayoutConstraints( 1, 0 ) ); - consultasPanel.add( prestadoresConsultasCombo, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - consultasPanel.add( enviarConsultasButton, new TableLayoutConstraints( 0, 2, 1, 2 ) ); -// consultasPanel.add( faxConsultasButton, new TableLayoutConstraints( 0, 3, 1, 3 ) ); - - rows = new double[]{ TableLayout.FILL, TableLayout.MINIMUM }; - - tableLayout = new TableLayout( cols,rows ); - ecdsPanel.setLayout( tableLayout ); -// -// ecdsPanel.add( ecdsLabel, new TableLayoutConstraints( 0, 0 ) ); -// ecdsPanel.add( numeroECDsLabel, new TableLayoutConstraints( 1, 0 ) ); -// ecdsPanel.add( prestadoresECDsCombo, new TableLayoutConstraints( 0, 1, 1, 1 ) ); - ecdsPanel.add( listaEcdsScroll, new TableLayoutConstraints( 0, 0, 1, 0 ) ); - ecdsPanel.add( enviarECDsButton, new TableLayoutConstraints( 0, 1, 1, 1 ) ); -// ecdsPanel.add( faxECDsButton, new TableLayoutConstraints( 0, 3, 1, 3 ) ); - -// cols = new double[]{ TableLayout.FILL }; -// rows = new double[]{ TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.FILL }; -// -// tableLayout = new TableLayout( cols,rows ); -// detalhesPanel.setLayout( tableLayout ); -// -// detalhesPanel.add( consultasPanel, new TableLayoutConstraints( 0, 0 ) ); -// detalhesPanel.add( ecdsPanel, new TableLayoutConstraints( 0, 1 ) ); - - setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); - addWindowListener( new WindowAdapter(){ - public void windowClosing( WindowEvent e ) - { - close(); - } - - public void windowOpened( WindowEvent e ) - { -// setExtendedState( getExtendedState() | MAXIMIZED_BOTH ); - } - - } ); - dataPanel.setDate( new Date() ); - recarregarPrestadores(); - carregar(); - } - - public void refresh() - { - } - - public void open() - { - setVisible( true ); - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable() { - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - public boolean closeIfPossible() - { - close(); - return true; - } - - public void actionPerformed(ActionEvent e) - { - Object source = e.getSource(); - if( source.equals( carregarButton ) ) - { - carregar(); - } -//// else if( source.equals( recarregarPrestadoresButton ) ) -// { -// recarregarPrestadores(); -// } - else if( source.equals( enviarConsultasButton ) ) - { - enviarConsultas(); - } - else if( source.equals( faxConsultasButton ) ) - { - faxConsultas(); - } - else if( source.equals( enviarECDsButton ) ) - { - enviarECDs(); - } -// else if( source.equals( faxECDsButton ) ) -// { -// faxECDs(); -// } - - } - - public void valueChanged(ListSelectionEvent e) - { - Object source = e.getSource(); - if( e.getValueIsAdjusting() ) - { - return; - } - if( source.equals( empresasTable.getSelectionModel() ) ) - { - mudarEmpresa(); - } - else if( source.equals( estabelecimentosTable.getSelectionModel() ) ) - { - mudarEstabelecimento(); - } - } - - protected void carregar() - { - empresasTable.clearSelection(); - Date data = dataPanel.getDate(); - if( data == null ) - { - empresasModel.clearAll(); - return; - } - try - { - ColumnizedMappable empresas[] = provider.getEmpresasComMarcacoes( data ); - Vector values = empresasModel.getValues(); - values.clear(); - values.addAll( Arrays.asList( empresas ) ); - empresasModel.setValues( values ); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar empresas", true ); - } - } - - protected void mudarEmpresa() - { - estabelecimentosTable.clearSelection(); - Date data = dataPanel.getDate(); - int selected = empresasTable.getSelectedRow(); - if( data == null || selected == -1 ) - { - estabelecimentosModel.clearAll(); - return; - } - Integer empresaID = ( ( ColumnizedMappable ) empresasModel.getRowAt( selected ) ).getID(); - try - { - ColumnizedMappable estabelecimentos[] = - provider.getEstabelecimentosComMarcacoesByEmpresa( empresaID, data ); - Vector values = estabelecimentosModel.getValues(); - values.clear(); - values.addAll( Arrays.asList( estabelecimentos ) ); - estabelecimentosModel.setValues( values ); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar estabelecimentos", true ); - } - } - - protected void mudarEstabelecimento() - { - Date data = dataPanel.getDate(); - int selectedEstabelecimento = estabelecimentosTable.getSelectedRow(); - numeroConsultasLabel.setText( " " ); -// numeroECDsLabel.setText( " " ); - enviarConsultasButton.setEnabled( false ); - enviarECDsButton.setEnabled( false ); - if( data == null || selectedEstabelecimento == -1 ) - { - return; - } - Integer estabelecimentoID = ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( selectedEstabelecimento ) ).getID(); - try - { - int countConsultas = - provider.getNumeroConsultasByEstabelecimentoAndDate( estabelecimentoID, data ); -// int countECDs = -// provider.getNumeroMarcacoesByEstabelecimentoAndTipo( estabelecimentoID, -// Marcacao.TIPO_MARCACAO_TRABALHADOR_EXAMES, data ); - if( countConsultas > 0 ) - { - numeroConsultasLabel.setText( "" + countConsultas ); - enviarConsultasButton.setEnabled( true ); - Integer[] escolhidos = - provider.getPrestadoresConsultaIdByEstabelecimentoAndDate( estabelecimentoID, data ); - if( escolhidos.length == 1 ) - { - numeroConsultasLabel.setForeground( Color.green.darker() ); - } - else - { - numeroConsultasLabel.setForeground( Color.red.darker() ); - } - int e; - for( e = 0; e < escolhidos.length; e++ ) - { - if( escolhidos[ e ] != null ) - { - break; - } - } - if( e == escolhidos.length || escolhidos[ e ] == null ) - { - prestadoresConsultasCombo.setSelectedIndex( 0 ); - } - else - { - for( int p = 0; p < prestadoresConsultasCombo.getItemCount(); p++ ) - { - IDObject prestador = ( IDObject ) prestadoresConsultasCombo.getItemAt( p ); - if( prestador.getID().equals( escolhidos[ e ] ) ) - { - prestadoresConsultasCombo.setSelectedIndex( p ); - } - } - } - enviarConsultasButton.setEnabled( true ); - } - - IDObject prestadoresECDs[] = prestadoresProvider.getPrestadoresECDsActivos(); - - IDObject gruposEcds[] = provider.getGruposEcdsByEstabelecimentoAndDate( estabelecimentoID, data ); - idsGruposEcds = new Integer[ gruposEcds.length ]; - prestadoresECDsCombos = new JComboBox[ gruposEcds.length ]; - JPanel gruposEcdsPanel = new JPanel(); - double rows[] = new double[ gruposEcds.length + 1 ]; - for( int n = 0; n < rows.length - 1; n++ ) - { - rows[ n ] = TableLayoutConstraints.MINIMUM; - } - rows[ rows.length - 1 ] = TableLayoutConstraints.FILL; - TableLayout layout = - new TableLayout( - new double[]{ TableLayoutConstraints.FILL, TableLayoutConstraints.MINIMUM, - TableLayoutConstraints.FILL }, - rows ); - gruposEcdsPanel.setLayout( layout ); - gruposEcdsPanel.setBorder( - BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), - "Protocolo" ) ); - for( int n = 0; n < gruposEcds.length; n++ ) - { - JLabel ecdLabel = new JLabel( "" + gruposEcds[ n ].toString() ); - int numero = - provider.getNumeroMarcacoesByGrupoEcdEstabelecimentoAndDate( - gruposEcds[ n ].getID(), estabelecimentoID, data ); - Integer escolhidos[] = - provider.getPrestadoresByGrupoEcdEstabelecimentoAndDate( - gruposEcds[ n ].getID(), estabelecimentoID, data ); - JLabel numeroLabel = new JLabel( "" + numero, JLabel.RIGHT ); - if( escolhidos.length > 1 ) - { - numeroLabel.setForeground( Color.red.darker() ); - } - else - { - numeroLabel.setForeground( Color.green.darker() ); - } - prestadoresECDsCombos[ n ] = new JComboBox(); - prestadoresECDsCombos[ n ].addItem( LocaisRealizacaoConstants.PRESTADOR_SIPRP ); - for( int p = 0; p < prestadoresECDs.length; p++ ) - { - prestadoresECDsCombos[ n ].addItem( prestadoresECDs[ p ] ); - } - int e; - for( e = 0; e < escolhidos.length; e++ ) - { - if( escolhidos[ e ] != null ) - { - break; - } - } - if( e == escolhidos.length || escolhidos[ e ] == null ) - { - prestadoresECDsCombos[ n ].setSelectedIndex( 0 ); - } - else - { - for( int p = 0; p < prestadoresECDsCombos[ n ].getItemCount(); p++ ) - { - IDObject prestador = ( IDObject ) prestadoresECDsCombos[ n ].getItemAt( p ); - if( prestador.getID().equals( escolhidos[ e ] ) ) - { - prestadoresECDsCombos[ n ].setSelectedIndex( p ); - } - } - } - - gruposEcdsPanel.add( ecdLabel, new TableLayoutConstraints( 0, n ) ); - gruposEcdsPanel.add( numeroLabel, new TableLayoutConstraints( 1, n ) ); - gruposEcdsPanel.add( prestadoresECDsCombos[ n ], new TableLayoutConstraints( 2, n ) ); - } - - - IDObject ecdsOficiais[] = provider.getExamesOficiaisByEstabelecimentoAndDate( estabelecimentoID, data ); - idsEcdsOficiais = new Integer[ ecdsOficiais.length ]; - prestadoresECDsOficiaisCombos = new JComboBox[ ecdsOficiais.length ]; - JPanel ecdsOficiaisPanel = new JPanel(); - rows = new double[ ecdsOficiais.length + 1 ]; - for( int n = 0; n < rows.length - 1; n++ ) - { - rows[ n ] = TableLayoutConstraints.MINIMUM; - } - rows[ rows.length - 1 ] = TableLayoutConstraints.FILL; - layout = new TableLayout( - new double[]{ TableLayoutConstraints.FILL, TableLayoutConstraints.MINIMUM, - TableLayoutConstraints.FILL }, - rows ); - ecdsOficiaisPanel.setLayout( layout ); - ecdsOficiaisPanel.setBorder( - BorderFactory.createTitledBorder( - BorderFactory.createEtchedBorder(), - "Extra protocolo" ) ); - for( int n = 0; n < ecdsOficiais.length; n++ ) - { - JLabel ecdLabel = new JLabel( "" + ecdsOficiais[ n ].toString() ); - int numero = - provider.getNumeroMarcacaoesByEcdOficialEstabelecimentoAndDate( - ecdsOficiais[ n ].getID(), estabelecimentoID, data ); - Integer escolhidos[] = - provider.getPrestadoresByEcdOficialEstabelecimentoAndDate( - ecdsOficiais[ n ].getID(), estabelecimentoID, data ); - JLabel numeroLabel = new JLabel( "" + numero, JLabel.RIGHT ); - if( escolhidos.length > 1 ) - { - numeroLabel.setForeground( Color.red.darker() ); - } - else - { - numeroLabel.setForeground( Color.green.darker() ); - } - prestadoresECDsOficiaisCombos[ n ] = new JComboBox(); - prestadoresECDsOficiaisCombos[ n ].addItem( LocaisRealizacaoConstants.PRESTADOR_SIPRP ); - for( int p = 0; p < prestadoresECDs.length; p++ ) - { - prestadoresECDsOficiaisCombos[ n ].addItem( prestadoresECDs[ p ] ); - } - int e; - for( e = 0; e < escolhidos.length; e++ ) - { - if( escolhidos[ e ] != null ) - { - break; - } - } - if( e == escolhidos.length || escolhidos[ e ] == null ) - { - prestadoresECDsOficiaisCombos[ n ].setSelectedIndex( 0 ); - } - else - { - for( int p = 0; p < prestadoresECDsOficiaisCombos[ n ].getItemCount(); p++ ) - { - IDObject prestador = ( IDObject ) prestadoresECDsOficiaisCombos[ n ].getItemAt( p ); - if( prestador.getID().equals( escolhidos[ e ] ) ) - { - prestadoresECDsOficiaisCombos[ n ].setSelectedIndex( p ); - } - } - } - - ecdsOficiaisPanel.add( ecdLabel, new TableLayoutConstraints( 0, n ) ); - ecdsOficiaisPanel.add( numeroLabel, new TableLayoutConstraints( 1, n ) ); - ecdsOficiaisPanel.add( prestadoresECDsOficiaisCombos[ n ], new TableLayoutConstraints( 2, n ) ); - } - - JPanel ecdsPanel = new JPanel(); - TableLayout ecdsLayout = - new TableLayout( new double[]{ TableLayoutConstraints.FILL }, - new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.MINIMUM, - TableLayoutConstraints.FILL } ); - ecdsPanel.setLayout( ecdsLayout ); - ecdsPanel.add( gruposEcdsPanel, new TableLayoutConstraints( 0, 0 ) ); - ecdsPanel.add( ecdsOficiaisPanel, new TableLayoutConstraints( 0, 1 ) ); - listaEcdsScroll.setViewportView( ecdsPanel ); - - enviarECDsButton.setEnabled( true ); -// if( countECDs > 0 ) -// { -// numeroECDsLabel.setText( "" + countECDs ); -// enviarECDsButton.setEnabled( true ); -// Integer[] escolhidos = -// provider.getPrestadoresIDByEstabelecimentoAndTipo( estabelecimentoID, -// Marcacao.TIPO_MARCACAO_TRABALHADOR_EXAMES, data ); -// if( escolhidos.length == 1 ) -// { -// numeroECDsLabel.setForeground( Color.green.darker() ); -// } -// else -// { -// numeroECDsLabel.setForeground( Color.red.darker() ); -// } -// int e; -// for( e = 0; e < escolhidos.length; e++ ) -// { -// if( escolhidos[ e ] != null ) -// { -// break; -// } -// } -// if( e == escolhidos.length || escolhidos[ e ] == null ) -// { -// prestadoresECDsCombo.setSelectedIndex( 0 ); -// } -// else -// { -// for( int p = 0; p < prestadoresECDsCombo.getItemCount(); p++ ) -// { -// IDObject prestador = ( IDObject ) prestadoresECDsCombo.getItemAt( p ); -// if( prestador.getID().equals( escolhidos[ e ] ) ) -// { -// prestadoresECDsCombo.setSelectedIndex( p ); -// } -// } -// } -// } - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar detalhes", true ); - } - } - - protected void recarregarPrestadores() - { - try - { - IDObject prestadoresConsultas[] = prestadoresProvider.getPrestadoresConsultasActivos(); - IDObject prestadoresECDs[] = prestadoresProvider.getPrestadoresECDsActivos(); - prestadoresConsultasCombo.removeAllItems(); - prestadoresConsultasCombo.addItem( LocaisRealizacaoConstants.PRESTADOR_SIPRP ); - for( int n = 0; n < prestadoresConsultas.length; n++ ) - { - prestadoresConsultasCombo.addItem( prestadoresConsultas[ n ] ); - } -// prestadoresECDsCombo.removeAllItems(); -// prestadoresECDsCombo.addItem( PRESTADOR_SIPRP ); -// for( int n = 0; n < prestadoresECDs.length; n++ ) -// { -// prestadoresECDsCombo.addItem( prestadoresECDs[ n ] ); -// } - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a carregar prestadores", true ); - } - } - - protected void enviarECDs() - { - Date data = dataPanel.getDate(); - int selectedEstabelecimento = estabelecimentosTable.getSelectedRow(); - if( data == null || selectedEstabelecimento == -1 ) - { - return; - } - Integer estabelecimentoID = ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( selectedEstabelecimento ) ).getID(); - try - { -// Integer prestadorID = ( ( IDObject ) prestadoresECDsCombo.getSelectedItem() ).getID(); -// if( PRESTADOR_ID_SIPRP.equals( prestadorID ) ) -// { -// prestadorID = null; -// } -// provider.setPrestadorIDForEstabelecimentoAndTipo( estabelecimentoID, -// Marcacao.TIPO_MARCACAO_TRABALHADOR_EXAMES, data, prestadorID ); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a atribuir", true ); - } - } - -// protected void faxECDs() -// { -// Date data = dataPanel.getDate(); -// int selectedEstabelecimento = estabelecimentosTable.getSelectedRow(); -// if( data == null || selectedEstabelecimento == -1 ) -// { -// return; -// } -// Integer estabelecimentoID = ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( selectedEstabelecimento ) ).getID(); -// try -// { -// Integer prestadorID = ( ( IDObject ) prestadoresECDsCombo.getSelectedItem() ).getID(); -// if( PRESTADOR_ID_SIPRP.equals( prestadorID ) ) -// { -// prestadorID = null; -// } -// provider.setPrestadorIDForEstabelecimentoAndTipo( estabelecimentoID, -// Marcacao.TIPO_MARCACAO_TRABALHADOR_EXAMES, data, prestadorID ); -// } -// catch( Exception ex ) -// { -// DialogException.showExceptionMessage( ex, "Erro a atribuir", true ); -// } -// } - - protected void enviarConsultas() - { - Date data = dataPanel.getDate(); - int selectedEstabelecimento = estabelecimentosTable.getSelectedRow(); - if( data == null || selectedEstabelecimento == -1 ) - { - return; - } - Integer estabelecimentoID = ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( selectedEstabelecimento ) ).getID(); - try - { - Integer prestadorID = ( ( IDObject ) prestadoresConsultasCombo.getSelectedItem() ).getID(); - if( LocaisRealizacaoConstants.PRESTADOR_ID_SIPRP.equals( prestadorID ) ) - { - prestadorID = null; - } - provider.setPrestadorConsultaIdForEstabelecimentoAndDate( estabelecimentoID, data, prestadorID ); - } - catch( Exception ex ) - { - DialogException.showExceptionMessage( ex, "Erro a atribuir", true ); - } - } - - protected void faxConsultas() - { - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds.xsl b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds.xsl deleted file mode 100644 index 6b5e07a7..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds.xsl +++ /dev/null @@ -1,283 +0,0 @@ - - - - - - - - - - - - - FAX - - Nº de Páginas (incluíndo esta) - / - Number of pages (including this one): - - - - - - - - - - - - - - Data - / - Date: - - - - - - - - - - - - Para - / - To: - - - - - - - - - - - - Empresa - / - Company: - - - - - - - - - - - - Nº Fax - / - Fax number: - - - - - - - - - - - - De - / - From: - - - - - - - - - E-mail: - - - - - - - - - - - Nº Fax - / - Fax number: - - - - - - - - - - Nº Tel. - / - Phone number: - - - - - - - - - - - - - - - - - - - - Assunto - / - Subject: - - - - - - - - - - - - - - - - - - - Cliente: - - - - - - - - Local: - - - - - - - - - - Data: - - - - - - - - Hora: - - - - - - - - - - Exmos. Senhores, - - Informo que o - s - seguinte - s - colaborador - es - irão - irá - comparecer nas vossas instalações para colheita: - - - - - - - - - NOME DO FUNCIONÁRIO - - - DATA_NASCIMENTO - - - PERFIL - - - - - - - - - - - - - - - - - - - - - - - - - - - PERFIL - - - : - - , - - - - - - - - - - AGRADEÇO QUE ESTA LISTAGEM NOS SEJA REENVIADA COM INDICAÇÃO DAS - EVENTUAIS FALTAS OCORRIDAS - - - - - Sem outro assunto de momento, aproveitamos para apresentar os nossos melhores cumprimentos, - - - - - - - - - - diff --git a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds_teste.xml b/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds_teste.xml deleted file mode 100644 index 8e0366c2..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/locais_realizacao/fax_ecds_teste.xml +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - 24-01-2007 - Pedro Manuel Silva Bento - Laboratorio ao lado da mercearia - 21 351 45 67 - Paula Dias - pdias@siprp.pt - (+351) 21 789 88 32 - (+351) 21 789 88 32 - Marcação de Colheitas para Análise - Evolute - Laboratorio ao lado da mercearia - 28-01-2007 - 08H00 - 1 - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - Frederico Alexandre de Matos Monge Palma - 02-10-1976 - 1 - - - Pedro da Silva Antonio - 02-10-1973 - 2 - - - Joao Pedro Silva - 02-10-1976 - 1 - - - - GENÉRICO - Hemograma - Vel. Sedimentação - Glicemia em Jejum - Creatinina - Colesterol Total - Colesterol HDL - Triglicéridos - Transaminases - Gama GT - Urina II - - - MANIPULADORES - Hemograma - Vel. Sedimentação - Glicemia em Jejum - Creatinina - Colesterol Total - Colesterol HDL - Triglicéridos - Transaminases - Gama GT - Urina II - Quistos - - diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/ColorChooserDialog.java b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/ColorChooserDialog.java deleted file mode 100644 index cc03d174..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/ColorChooserDialog.java +++ /dev/null @@ -1,103 +0,0 @@ -package siprp.medicina.processo.mail; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import javax.swing.colorchooser.AbstractColorChooserPanel; - -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.ui.CustomJDialog; - -public class ColorChooserDialog extends CustomJDialog - implements ActionListener -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - protected JColorChooser colorChooser; - protected JButton okButton; - protected JButton cancelButton; - - protected Color initialColor; - protected Color selectedColor; - - public ColorChooserDialog( SIPRPFrame owner, Color color ) - { - super( owner, true ); - initialColor = color; - setupComponents(); - if( owner != null ) - { - centerSuper(); - } - else - { - center(); - } - } - - private void setupComponents() - { - setTitle( "Escolha a cor" ); - colorChooser = new JColorChooser( initialColor ); - - colorChooser.setChooserPanels( new AbstractColorChooserPanel[]{ colorChooser.getChooserPanels()[ 0 ] } ); - colorChooser.setPreviewPanel( new JPanel() ); - okButton = new JButton( "OK" ); - cancelButton = new JButton( "Cancelar" ); - - setLayout( new BorderLayout() ); - add( colorChooser, BorderLayout.CENTER ); - JPanel buttonPanel = new JPanel(); - add( buttonPanel, BorderLayout.SOUTH ); - - buttonPanel.setLayout( new FlowLayout( FlowLayout.CENTER ) ); - buttonPanel.add( okButton ); - buttonPanel.add( cancelButton ); - - okButton.addActionListener( this ); - cancelButton.addActionListener( this ); - pack(); - } - - @Override - public void actionPerformed(ActionEvent e) - { - Object source = e.getSource(); - if( source.equals( okButton ) ) - { - selectedColor = colorChooser.getColor(); - close(); - } - else - { - close(); - } - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable(){ - public void run() - { - setVisible( false ); - dispose(); - } - } ); - } - - public Color getColor() - { - return selectedColor; - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailDialog.java b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailDialog.java deleted file mode 100644 index 0e865fec..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailDialog.java +++ /dev/null @@ -1,645 +0,0 @@ -package siprp.medicina.processo.mail; - -import info.clearthought.layout.TableLayout; -import info.clearthought.layout.TableLayoutConstraints; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.FileDialog; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.io.File; -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Vector; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ActionMap; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JTextPane; -import javax.swing.SwingUtilities; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.text.AttributeSet; -import javax.swing.text.DefaultEditorKit; -import javax.swing.text.StyleConstants; -import javax.swing.text.StyledEditorKit; -import javax.swing.text.html.HTMLEditorKit; - -import siprp.ui.SIPRPFrame; - -import com.evolute.utils.images.ImageIconLoader; -import com.evolute.utils.tables.BaseTable; -import com.evolute.utils.tables.VectorTableModel; -import com.evolute.utils.ui.CustomJDialog; - -public class MailDialog extends CustomJDialog -{ - /** - * - */ - private static final long serialVersionUID = 1L; - protected StyledEditorKit.FontSizeAction FONT_SIZE_ACTIONS[]; - protected int FONT_SIZES[]; - - protected SIPRPFrame owner; - - protected JTextField toText; - protected JTextField bccText; - protected JTextField subjectText; - protected BaseTable attachmentsTable; - protected VectorTableModel attachmentsModel; - protected JTextPane bodyPane; - - protected Action removeAttachmentAction; - - private boolean sent = false; -// -// public static void main( String args[] ) -// throws Exception -// { -// MailDialog mailDialog = new MailDialog( null ); -// mailDialog.setTo( "fredPalma@netcabo.pt" ); -// mailDialog.setBcc( "fpalma@evolute.pt" ); -// mailDialog.setSubject( "SIPRP - Marca\u00E7\u00E3o de consulta de 'Frederico Palma'" ); -// mailDialog.setMessage( -// "

" -// + "Vimos pelo presente informar que 'Frederico Palma' deverá comparecer " -// + "nas nossas instalações para a realização da consulta de Medicina " -// + "do Trabalho, no dia '10-01-2008', pelas 08H30. " -// + "

" -// + "

" -// + "Solicitamos, também, que o colaborador seja portador do Boletim de Vacinas e " -// + "dos últimos exames complementares realizados." -// + "

" -// + "

" -// + "Caso não seja possível a comparência deste colaborador na data " -// + "indicada, contacte-nos, por favor, através do telefone 21 350 45 40 " -// + "ou respondendo ao remetente desta mensagem." -// + "

" -// + "

" -// + "Cumprimentos," -// + "

" -// + "

" -// + "SIPRP" -//// color=\"#497895\" -// + "

" -// + "

" -// + "ATRIUM SALDANHA" -// + "

" -// + "

" -// + "Praça Duque de Saldanha, 1 - 9ºG" -// + "

" -// + "

" -// + "1050-094 Lisboa" -// + "

" ); -// mailDialog.setSize( 1024, 768 ); -// mailDialog.setVisible( true ); -// System.exit( 0 ); -// } - - private final String[] additionalBCCs; - - public MailDialog( SIPRPFrame owner, String to, String bcc, String subject, String message, Vector files, String ... additionalBCCs) - throws Exception - { - super( owner, true ); - this.additionalBCCs = additionalBCCs; - this.owner = owner; - commonStartup(); - setTo( to ); - setBcc( bcc ); - setSubject( subject ); - setMessage( message ); - attach( files ); - setModal( true ); - setSize( 800, 600 ); - setLocationRelativeTo( null ); - setVisible( true ); - } - -// public MailDialog( SIPRPFrame owner ) -// throws Exception -// { -// super( owner, true ); -// this.owner = owner; -// commonStartup(); -// setModal( true ); -// setSize( 1024, 768 ); -// setVisible( true ); -// } - - private void commonStartup() - throws Exception - { - setupComponents(); - if( owner != null ) - { - centerSuper(); - } - else - { - center(); - } - } - - private void setupComponents() - throws Exception - { - setLayout( new BorderLayout() ); - JPanel headerPanel = new JPanel(); - setupHeaderComponents( headerPanel ); - add( headerPanel, BorderLayout.NORTH ); - JPanel htmlPanel = new JPanel(); - setupHTMLComponents( htmlPanel ); - add( htmlPanel, BorderLayout.CENTER ); - } - - private void setupHeaderComponents( JPanel headerPanel ) - throws Exception - { - Action sendAction = new AbstractAction( "send" ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - try - { - setCursor( new Cursor(Cursor.WAIT_CURSOR) ); - send(); - } - finally - { - setCursor( new Cursor(Cursor.DEFAULT_CURSOR ) ); - } - close(); - } - }; - sendAction.putValue( Action.SHORT_DESCRIPTION, "Enviar" ); - JButton sendButton = createButton( sendAction, "siprp/medicina/processo/mail/icons/mail2.png" ); - Action attachAction = new AbstractAction( "attach" ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - FileDialog fd = new FileDialog( owner, "Escolha um ficheiro", FileDialog.LOAD ); - fd.setDirectory( System.getProperty( "user.home" ) ); - fd.setVisible( true ); - // String filename = "c:\\test.xls"; - String filename = fd.getFile(); - if( filename != null ) - { - String dir = fd.getDirectory(); - attach( filename, dir ); - } - } - }; - attachAction.putValue( Action.SHORT_DESCRIPTION, "Acrescentar anexo" ); - JButton attachButton = createButton( attachAction, "siprp/medicina/processo/mail/icons/mail_attachment.png" ); - removeAttachmentAction = new AbstractAction( "remove-attachment" ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - int selected = attachmentsTable.getSelectedRow(); - if( selected > -1 && selected < attachmentsTable.getRowCount() ) - { - attachmentsModel.removeRowAt( selected ); - } - } - }; - removeAttachmentAction.putValue( Action.SHORT_DESCRIPTION, "Remover anexo" ); - JButton removeAttachmentButton = createButton( removeAttachmentAction, "siprp/medicina/processo/mail/icons/delete2.png" ); - removeAttachmentAction.setEnabled( false ); - - JPanel buttonPanel = new JPanel(); - buttonPanel.setLayout( new GridLayout( 1, 2 ) ); - JPanel leftButtonPanel = new JPanel(); - buttonPanel.add( leftButtonPanel ); - JPanel rightButtonPanel = new JPanel(); -// buttonPanel.add( rightButtonPanel ); - leftButtonPanel.setLayout( new FlowLayout( FlowLayout.LEFT ) ); - leftButtonPanel.add( sendButton ); - rightButtonPanel.setLayout( new FlowLayout( FlowLayout.RIGHT ) ); - rightButtonPanel.add( attachButton ); - rightButtonPanel.add( removeAttachmentButton ); - - JLabel toLabel = new JLabel( "Para:" ); - toText = new JTextField(); - JLabel bccLabel = new JLabel( "C\u00f3pia:" ); - bccText = new JTextField(); - JLabel assuntoLabel = new JLabel( "Assunto:" ); - subjectText = new JTextField(); - attachmentsModel = new VectorTableModel( new String[]{ "" } ); - attachmentsTable = new BaseTable( attachmentsModel ); -// JScrollPane attachmentsScroll = new JScrollPane( attachmentsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, -// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); - attachmentsTable.getSelectionModel().addListSelectionListener( new ListSelectionListener(){ - - @Override - public void valueChanged(ListSelectionEvent e) - { - removeAttachmentAction.setEnabled( attachmentsTable.getSelectedRow() != -1 ); - } - - } ); - - TableLayout layout = - new TableLayout( - new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL }, - new double[]{ TableLayoutConstraints.PREFERRED, TableLayoutConstraints.MINIMUM, TableLayoutConstraints.MINIMUM, - TableLayoutConstraints.MINIMUM } ); - layout.setHGap( 2 ); - layout.setVGap( 2 ); - - headerPanel.setLayout( layout ); - headerPanel.add( buttonPanel, new TableLayoutConstraints( 0, 0, 1, 0 ) ); - headerPanel.add( toLabel, new TableLayoutConstraints( 0, 1 ) ); - headerPanel.add( toText, new TableLayoutConstraints( 1, 1 ) ); -// headerPanel.add( attachmentsScroll, new TableLayoutConstraints( 2, 1, 2, 3 ) ); - headerPanel.add( bccLabel, new TableLayoutConstraints( 0, 2 ) ); - headerPanel.add( bccText, new TableLayoutConstraints( 1, 2 ) ); - headerPanel.add( assuntoLabel, new TableLayoutConstraints( 0, 3 ) ); - headerPanel.add( subjectText, new TableLayoutConstraints( 1, 3 ) ); - } - - private void setupHTMLComponents( JPanel htmlPanel ) - throws Exception - { - HTMLEditorKit kit = new HTMLEditorKit(); - Action actions[] = kit.getActions(); - Vector fontSizeActions = - new Vector(); - for( int n = 0; n < actions.length; n++ ) - { - String str = actions[ n ].getValue( Action.NAME ).toString(); - if( str.toLowerCase().indexOf( "font-size" ) != -1 ) - { - int size = Integer.parseInt( str.split( "-" )[ 2 ] ); - if( size == 16 ) - { - continue; - } - fontSizeActions.add( ( StyledEditorKit.FontSizeAction ) actions[ n ] ); - } - } - - FONT_SIZE_ACTIONS = fontSizeActions.toArray( new StyledEditorKit.FontSizeAction[ fontSizeActions.size() ] ); - Arrays.sort( FONT_SIZE_ACTIONS, new Comparator(){ - public int compare( StyledEditorKit.FontSizeAction fsa1, StyledEditorKit.FontSizeAction fsa2 ) - { - String str1 = fsa1.getValue( Action.NAME ).toString(); - String str2 = fsa2.getValue( Action.NAME ).toString(); - int size1 = Integer.parseInt( str1.split( "-" )[ 2 ] ); - int size2 = Integer.parseInt( str2.split( "-" )[ 2 ] ); - return size1 > size2 ? 1 : -1; - } - } ); - FONT_SIZES = new int[ FONT_SIZE_ACTIONS.length ]; - for( int n = 0; n < FONT_SIZES.length; n++ ) - { - FONT_SIZES[ n ] = Integer.parseInt( FONT_SIZE_ACTIONS[ n ].getValue( Action.NAME ).toString().split( "-" )[ 2 ] ); - } - - bodyPane = new JTextPane(); - bodyPane.setEditorKit( kit ); - ActionMap actionMap = bodyPane.getActionMap(); - - Action cutAction = actionMap.get( DefaultEditorKit.cutAction ); - cutAction.putValue( Action.SHORT_DESCRIPTION, "Cortar" ); - Action copyAction = actionMap.get( DefaultEditorKit.copyAction ); - copyAction.putValue( Action.SHORT_DESCRIPTION, "Copiar" ); - Action pasteAction = actionMap.get( DefaultEditorKit.pasteAction ); - pasteAction.putValue( Action.SHORT_DESCRIPTION, "Colar" ); - - Action boldAction = actionMap.get( "font-bold" ); - boldAction.putValue( Action.SHORT_DESCRIPTION, "Bold" ); - Action italicAction = actionMap.get( "font-italic" ); - italicAction.putValue( Action.SHORT_DESCRIPTION, "It\u00e1lico" ); - Action underlineAction = actionMap.get( "font-underline" ); - underlineAction.putValue( Action.SHORT_DESCRIPTION, "Sublinhado" ); - Action fontBiggerAction = new StyledEditorKit.FontSizeAction( "font-bigger", 30 ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - - int start = bodyPane.getSelectionStart(); - AttributeSet set = bodyPane.getStyledDocument().getCharacterElement( start ).getAttributes(); - int size = StyleConstants.getFontSize( set ); - for( int n = 0; n < FONT_SIZES.length; n++ ) - { - if( size < FONT_SIZES[ n ] ) - { - FONT_SIZE_ACTIONS[ n ].actionPerformed( e ); - break; - } - } - bodyPane.requestFocusInWindow(); - } - }; - fontBiggerAction.putValue( Action.SHORT_DESCRIPTION, "Fonte maior" ); - Action fontSmallerAction = - new StyledEditorKit.FontSizeAction( "font-smaller", 5 ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - - int start = bodyPane.getSelectionStart(); - AttributeSet set = bodyPane.getStyledDocument().getCharacterElement( start ).getAttributes(); - int size = StyleConstants.getFontSize( set ); - for( int n = FONT_SIZES.length - 1; n >= 0; n-- ) - { - if( size > FONT_SIZES[ n ] ) - { - FONT_SIZE_ACTIONS[ n ].actionPerformed( e ); - break; - } - } - bodyPane.requestFocusInWindow(); - } - }; - fontSmallerAction.putValue( Action.SHORT_DESCRIPTION, "Fonte menor" ); - Action colorAction = - new StyledEditorKit.ForegroundAction( "color", Color.black ){ - /** - * - */ - private static final long serialVersionUID = 1L; - - public void actionPerformed( ActionEvent e ) - { - ColorChooserDialog dialog = new ColorChooserDialog( owner, Color.black ); - dialog.setVisible( true ); - Color color = dialog.getColor(); - if( color != null ) - { - bodyPane.requestFocusInWindow(); - Action colorTempAction = new StyledEditorKit.ForegroundAction( "color-temp", color ); - bodyPane.getActionMap().put( "color-temp", colorTempAction ); - colorTempAction.actionPerformed( e ); - } - bodyPane.requestFocusInWindow(); - } - }; - colorAction.putValue( Action.SHORT_DESCRIPTION, "C\u00f4r" ); - String fontFamilies[] = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); - JComboBox fontCombo = new JComboBox(); - for( int n = 0; n < fontFamilies.length; n++ ) - { - fontCombo.addItem( fontFamilies[ n ] ); - } - fontCombo.addItemListener( new ItemListener(){ - - @Override - public void itemStateChanged(ItemEvent e) - { - String selected = ( String ) e.getItem(); - Action fontFamilyAction = - new StyledEditorKit.FontFamilyAction( "font-family-action" , selected ); - bodyPane.getActionMap().put( "font-family-action", fontFamilyAction ); - fontFamilyAction.actionPerformed( - new ActionEvent( e.getSource(), e.getID(), "" ) ); - bodyPane.requestFocusInWindow(); - } - } ); - - Action alignLeftAction = actionMap.get( "left-justify" ); - alignLeftAction.putValue( Action.SHORT_DESCRIPTION, "Alinhado \u00e0 esquerda" ); - Action alignCenterAction = actionMap.get( "center-justify" ); - alignCenterAction.putValue( Action.SHORT_DESCRIPTION, "Centrado" ); - Action alignRightAction = actionMap.get( "right-justify" ); - alignRightAction.putValue( Action.SHORT_DESCRIPTION, "Alinhado \u00e0 direita" ); - Action alignJustifyAction = - new StyledEditorKit.AlignmentAction( "justify", - javax.swing.text.StyleConstants.ALIGN_JUSTIFIED ); - actionMap.put( "justify", alignJustifyAction ); - alignJustifyAction.putValue( Action.SHORT_DESCRIPTION, "Justificado" ); - - JButton exportButton = new JButton( "X" ); - exportButton.addActionListener( new ActionListener(){ - public void actionPerformed( ActionEvent e ) - { - System.out.println( bodyPane.getText() ); - } - } ); - - JPanel upperPanel = new JPanel(); - upperPanel.setLayout( new FlowLayout( FlowLayout.LEFT ) ); - upperPanel.add( exportButton ); - upperPanel.add( createButton( cutAction, "siprp/medicina/processo/mail/icons/cut.png" ) ); - upperPanel.add( createButton( copyAction, "siprp/medicina/processo/mail/icons/copy.png" ) ); - upperPanel.add( createButton( pasteAction, "siprp/medicina/processo/mail/icons/paste.png" ) ); - upperPanel.add( new JLabel( " " ) ); - upperPanel.add( createButton( boldAction, "siprp/medicina/processo/mail/icons/text_bold.png" ) ); - upperPanel.add( createButton( italicAction, "siprp/medicina/processo/mail/icons/text_italics.png" ) ); - upperPanel.add( createButton( underlineAction, "siprp/medicina/processo/mail/icons/text_underlined.png" ) ); - upperPanel.add( createButton( fontBiggerAction, "siprp/medicina/processo/mail/icons/font_bigger.png" ) ); - upperPanel.add( createButton( fontSmallerAction, "siprp/medicina/processo/mail/icons/font_smaller.png" ) ); - upperPanel.add( createButton( colorAction, "siprp/medicina/processo/mail/icons/colorwheel.png" ) ); - upperPanel.add( fontCombo ); - upperPanel.add( new JLabel( " " ) ); - upperPanel.add( createButton( alignLeftAction, "siprp/medicina/processo/mail/icons/text_align_left.png" ) ); - upperPanel.add( createButton( alignCenterAction, "siprp/medicina/processo/mail/icons/text_align_center.png" ) ); - upperPanel.add( createButton( alignRightAction, "siprp/medicina/processo/mail/icons/text_align_right.png" ) ); - upperPanel.add( createButton( alignJustifyAction, "siprp/medicina/processo/mail/icons/text_align_justified.png" ) ); - - htmlPanel.setLayout( new BorderLayout() ); - - htmlPanel.add( upperPanel, BorderLayout.NORTH ); - htmlPanel.add( new JScrollPane( bodyPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ), BorderLayout.CENTER ); - } - - private JButton createButton( Action action, String iconPath ) - throws Exception - { - action.putValue( Action.SMALL_ICON, ImageIconLoader.loadImageIcon( iconPath ) ); - JButton button = new JButton( action ); - button.setText( null ); - - return button; - } - - public void setTo( String to ) - { - toText.setText( to ); - } - - public String getTo() - { - return toText.getText(); - } - - public void setBcc( String bcc ) - { - bccText.setText( bcc ); - } - - public String getBcc() - { - return bccText.getText(); - } - - public void setSubject( String subject ) - { - subjectText.setText( subject ); - } - - public String getSubject() - { - return subjectText.getText(); - } - - public void setMessage( String message ) - { - bodyPane.setText( message ); - } - - public String getMessage() - { - return bodyPane.getText(); - } - - public void send() - { -// close(); - String to = toText.getText(); - String bcc = bccText.getText(); - if( additionalBCCs != null ) - { - String bccconcat = ""; - for( String b : additionalBCCs ) - { - bccconcat += b + ", "; - } - bcc = bccconcat + bcc; - if( bcc.endsWith( ", " ) ) - { - bcc = bcc.substring( 0, bcc.length() - 2 ); - } - } - String subject = subjectText.getText(); - String body = bodyPane.getText(); - String attachmentList[] = new String[ attachmentsTable.getRowCount() ]; - List attachments = new LinkedList(); - Vector values = attachmentsModel.getValues(); - for( int n = 0; n < attachmentList.length; n++ ) - { - String str = values.elementAt( n ); - String name = str.substring( 0, str.indexOf( "(") - 1 ); - String path = str.substring( str.indexOf( "(") + 1, str.indexOf( ")") ); -// try -// { - File file = new File(path + name); - if( file != null && file.exists() ) - { - attachments.add(file); - } -// FileInputStream fis = new FileInputStream( path + name ); -// Vector bytes = new Vector(); -// int available = 0; -// int total = 0; -// while( ( available = fis.available() ) > 0 ) -// { -// byte b[] = new byte[ available ]; -// fis.read( b ); -// bytes.add( b ); -// total += available; -// } -// attachments[ n ] = new byte[ total ]; -// int pos = 0; -// for( byte[] chunk : bytes ) -// { -// System.arraycopy( chunk, 0, attachments[ n ], pos, chunk.length ); -// pos += chunk.length; -// } -// } -// catch( FileNotFoundException fnfex ) -// { -// JOptionPane.showMessageDialog( owner, -// "O ficheiro " + path + name + " n\u00e3o existe.", -// "Ficheiro inexistente", -// JOptionPane.ERROR_MESSAGE ); -// return; -// } -// catch( IOException ioex ) -// { -// DialogException.showExceptionMessage( ioex, "Erro a ler ficheiro " + path + name, true ); -// return; -// } - } - MailSender sender = new MailSender(); - try - { - sender.send( to, bcc, subject, body, attachmentList, attachments ); - sent = true; - } - catch( Exception ex ) - { - ex.printStackTrace(); - } - } - - public boolean wasSent() - { - return sent; - } - - public void close() - { - SwingUtilities.invokeLater( new Runnable(){ - public void run() - { - setVisible( false ); - dispose(); - } - } ); - - } - - private void attach( Vector files ) - { - for (File file : files ) - { - attach( file.getName(), file.getParent() + File.separator ); - } - } - - public void attach( String filename, String dir ) - { - String full = filename + " (" + dir + ")"; - Vector values = attachmentsModel.getValues(); - values.add( full ); - attachmentsModel.setValues( values ); - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailSender.java b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailSender.java deleted file mode 100644 index 58f8d71d..00000000 --- a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/MailSender.java +++ /dev/null @@ -1,84 +0,0 @@ -package siprp.medicina.processo.mail; - -import java.io.File; -import java.util.Date; -import java.util.List; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.Address; -import javax.mail.Authenticator; -import javax.mail.Message; -import javax.mail.Multipart; -import javax.mail.PasswordAuthentication; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; - -public class MailSender -{ - public static final String from = "departamentotecnico@siprp.pt"; - protected String mailServer = "mail2.evolute.pt"; - protected String userName = "auto@siprp.pt"; - protected String password = "sdfoyias78e"; - - public MailSender() - { - - } - - public void send( String to, String bcc, String subject, String body, String attachmentNames[], List attachments ) throws Exception - { - Properties props = System.getProperties(); - props.put( "mail.smtp.host", mailServer ); - props.put( "mail.smtp.auth", "true" ); - - Authenticator auth = new SMTPAuthenticator(); - Session session = Session.getInstance( props, auth ); - - MimeMessage msg = new MimeMessage( session ); - - msg.setFrom( new InternetAddress( from ) ); - msg.setReplyTo( new Address[]{ new InternetAddress(from)} ); - msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to, true ) ); - msg.setRecipients( Message.RecipientType.CC, InternetAddress.parse( bcc, true ) ); - msg.setSubject( subject ); - - MimeBodyPart bodyPart = new MimeBodyPart(); - bodyPart.setContent( body,"text/html" ); - - Multipart multipart = new MimeMultipart(); - multipart.addBodyPart(bodyPart); - - if( attachmentNames != null && !attachments.isEmpty() ) - { - for(int i = 0; i < attachmentNames.length; ++i ) - { -// String attachName = attachmentNames[i]; - MimeBodyPart attachPart = new MimeBodyPart(); - DataSource dataSource = new FileDataSource(attachments.get(i)); - attachPart.setDataHandler( new DataHandler(dataSource)); - attachPart.setFileName(attachments.get(i).getName()); - multipart.addBodyPart(attachPart, i + 1); - } - } - msg.setContent(multipart); - msg.setHeader( "X-Mailer", "Evolute Mailer" ); - msg.setSentDate( new Date() ); - Transport.send( msg ); - } - - private class SMTPAuthenticator extends javax.mail.Authenticator - { - - public PasswordAuthentication getPasswordAuthentication() - { - return new PasswordAuthentication(userName, password); - } - } -} diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/Thumbs.db b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/Thumbs.db deleted file mode 100644 index d1514ff6..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/Thumbs.db and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/arrow_down.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/arrow_down.png deleted file mode 100644 index ad8f6a36..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/arrow_down.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/colorwheel.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/colorwheel.png deleted file mode 100644 index a655727e..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/colorwheel.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/copy.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/copy.png deleted file mode 100644 index 87cf5c96..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/copy.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/cut.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/cut.png deleted file mode 100644 index bb623773..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/cut.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/delete2.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/delete2.png deleted file mode 100644 index c617f7dc..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/delete2.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font.png deleted file mode 100644 index a87f6e45..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_bigger.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_bigger.png deleted file mode 100644 index 2f9217ee..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_bigger.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_smaller.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_smaller.png deleted file mode 100644 index e7dafe03..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/font_smaller.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail2.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail2.png deleted file mode 100644 index 6315fdc2..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail2.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail_attachment.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail_attachment.png deleted file mode 100644 index 668440ad..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/mail_attachment.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/paste.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/paste.png deleted file mode 100644 index e3397b27..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/paste.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_center.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_center.png deleted file mode 100644 index fceafc18..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_center.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_justified.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_justified.png deleted file mode 100644 index 639e7f63..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_justified.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_left.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_left.png deleted file mode 100644 index d930bf9d..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_left.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_right.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_right.png deleted file mode 100644 index 6570be7f..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_align_right.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_bold.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_bold.png deleted file mode 100644 index 4fb8dd90..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_bold.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_italics.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_italics.png deleted file mode 100644 index 14db2c1d..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_italics.png and /dev/null differ diff --git a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_underlined.png b/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_underlined.png deleted file mode 100644 index 0e5fb06c..00000000 Binary files a/trunk/SIPRPSoft/src/siprp/medicina/processo/mail/icons/text_underlined.png and /dev/null differ