Package clips.service.discount.card

Source Code of clips.service.discount.card.PanelDiscountCard$NumberFilter

/*
* PanelDiscountCard.java
*
* Created on 26 �?юль 2008 г., 12:02
*/
package clips.service.discount.card;

import beans.UserRightsSet;
import cli_fmw.delegate.DelegateLine2;
import cli_fmw.delegate.directory.complex.DirectoryLocator;
import clips.delegate.directory.simple.discountCard.DirectoryDiscountCardTypeItem;
import clips.delegate.service.discount.DiscountCardLocal;
import cli_fmw.main.PageContainer;
import cli_fmw.main.PageGeneric;
import cli_fmw.main.Persistentable;
import cli_fmw.utils.MessageBox;
import cli_fmw.main.ClipsException;
import cli_fmw.utils.DefaultColors;
import cli_fmw.utils.delegate_models.DelegateDateModel;
import cli_fmw.utils.table_config_states.StateSaver;
import clips.delegate.directory.ro.DirectoryCollaboratorItem;
import clips.delegate.directory.simple.discountCard.DirectoryDiscountCardType;
import clips.login.UserInfo;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
* Панель редактирования дисконтной карты
* @author  petr
*/
public class PanelDiscountCard extends PageGeneric
        implements Persistentable {

    private DiscountCardLocal cardLocal;//карта
    //бубен для ввода денег на карте
    private boolean useSeparator;//сепаратор был использован
    private Character separator; //сепаратор из настроек системы
    private MoneyListener moneyListener;

    /**
     * Слушатель ввода суммы
     */
    private class MoneyListener implements DocumentListener {

        @Override
        public void insertUpdate(DocumentEvent e) {
            changeMoney();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            changeMoney();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            changeMoney();
        }

        /**
         * Изменение суммы на карте
         */
        private void changeMoney() {
            try {
                String text = tfMoney.getText();
                if (text.isEmpty()) {
                    text = "0";
                }
                if (text.indexOf(separator) < 0) {//Бубен
                    useSeparator = false;
                } else {
                    useSeparator = true;
                }
                Number v = NumberFormat.getInstance().parse(text);
                double d = v.doubleValue();
                int money = (int) (d * 100);
                cardLocal.setMoney(money);
            } catch (ParseException ex) {
                MessageBox.showWarning(MessageBox.W_INCORRECT_DATA);
            } catch (ClipsException ex) {
                MessageBox.showException(ex);
            }
        }
    }

   
    /**
     * Бубен
     * Фильтр для документа, возможно ввести тока числа и один раз сепаратор
     */
    private class NumberFilter extends DocumentFilter {

        @Override
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
                String text, AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, checkInput(text, offset), attrs);
        }

        private String checkInput(String proposedValue, int offset) throws BadLocationException {
            //Убиваем все нецЫфры
            String res = "";
            for (int i = 0; i < proposedValue.length(); i++) {
                Character ch = proposedValue.charAt(i);
                if (Character.isDigit(ch)) {
                    res += ch;
                } else if (ch.equals(separator) & !useSeparator) {
                    res += ch;
                    useSeparator = true;
                }

            }
            return res;
        }
    }

    /**
     * Конструктор панели
     * @param container пейдж-контейнер
     * @param cardLocal дисконтная карта
     * @throws generic.ClipsException
     */
    public PanelDiscountCard(PageContainer container, DiscountCardLocal cardLocal_) throws ClipsException {
        super(container);
        //возьмём сепаратор из системы
        DecimalFormatSymbols dd = DecimalFormatSymbols.getInstance();
        separator = dd.getDecimalSeparator();
        moneyListener = new MoneyListener();

        initComponents();

        DirectoryDiscountCardType directory = DirectoryLocator.getDirectory(DirectoryDiscountCardType.class);
        DefaultComboBoxModel model = new DefaultComboBoxModel(directory.toArray());
        cbCardType.setModel(model);
        this.cardLocal = cardLocal_;
        updateScreenFields(cardLocal);
        cardLocal.addContentStateListener(getContainer());

        new DelegateDateModel<DiscountCardLocal>(cardLocal_, dchCreated) {

            @Override
            protected Date getDateImp() throws ClipsException {
                return getDelegate().getCreatedDate();
            }

            @Override
            protected void setDateImp(Date date) throws ClipsException {
                getDelegate().setCreatedDate(date);
            }
        };
        new DelegateDateModel<DiscountCardLocal>(cardLocal_, dchExpired) {

            @Override
            protected Date getDateImp() throws ClipsException {
                return getDelegate().getExpiredDate();
            }

            @Override
            protected void setDateImp(Date date) throws ClipsException {
                getDelegate().setExpiredDate(date);
            }
        };
        new DelegateDateModel<DiscountCardLocal>(cardLocal_, dchLastUsed) {

            @Override
            protected Date getDateImp() throws ClipsException {
                return getDelegate().getLastUsed();
            }

            @Override
            protected void setDateImp(Date date) throws ClipsException {
                getDelegate().setLastUsed(date);
            }
        };
        tfMoney.getDocument().addDocumentListener(moneyListener);
    StateSaver.attachTo(this);
    }

    /**
     * Обновляет значения полей формы данными карты
     * @param cardLocal карта
     * @throws generic.ClipsException
     */
    private void updateScreenFields(DiscountCardLocal cardLocal) throws ClipsException {
        useSeparator = false;//настройка бубна
        tfFIO.setText(cardLocal.getClient().toString());
        tfCode.setText(cardLocal.getCode());

        NumberFilter filter = new NumberFilter();
        ((AbstractDocument) tfMoney.getDocument()).setDocumentFilter(filter);

        tfMoney.setText(String.format("%.2f", 0.01 * cardLocal.getMoney()));

        cbCardType.setSelectedItem(cardLocal.getCardType());
        DirectoryCollaboratorItem dci = cardLocal.getBlocker();
        if (dci == null) {
            tfBlock.setText("");
            btBlock.setText("Заблокировать");
            btBlock.setEnabled(UserInfo.get().check(UserRightsSet.BLOCK_DISCOUNT_CARD)
                    || UserInfo.get().isSuperUser());
        } else {
            tfBlock.setText("Заблокировано: " + dci.toString());
            tfBlock.setForeground(DefaultColors.TABLE_RED_FOREGROUND);
            btBlock.setText("Разблокировать");
            btBlock.setEnabled(UserInfo.get().isSuperUser());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        tfBlock = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        tfFIO = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        cbCardType = new javax.swing.JComboBox();
        tfCode = new javax.swing.JTextField();
        tfMoney = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        dchCreated = new org.infotechservice.ICalendar.components.ICDateChooser();
        jPanel7 = new javax.swing.JPanel();
        dchExpired = new org.infotechservice.ICalendar.components.ICDateChooser();
        jPanel8 = new javax.swing.JPanel();
        dchLastUsed = new org.infotechservice.ICalendar.components.ICDateChooser();
        jPanel10 = new javax.swing.JPanel();
        btBlock = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        setPreferredSize(new java.awt.Dimension(100, 100));
        setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.BorderLayout(5, 10));

        jPanel1.setLayout(new java.awt.GridLayout(9, 1, 0, 5));

        jLabel1.setText("Пациент");
        jPanel1.add(jLabel1);

        jLabel7.setText("Тип карты");
        jPanel1.add(jLabel7);

        jLabel2.setText("Код");
        jPanel1.add(jLabel2);

        jLabel3.setText("Накоплено");
        jPanel1.add(jLabel3);

        jLabel8.setText("Выдана");
        jPanel1.add(jLabel8);

        jLabel4.setText("Срок действия, до");
        jPanel1.add(jLabel4);

        jLabel5.setText("Последнее использование");
        jPanel1.add(jLabel5);

        tfBlock.setEditable(false);
        tfBlock.setText("заб/разб");
        jPanel1.add(tfBlock);

        jPanel2.add(jPanel1, java.awt.BorderLayout.LINE_START);

        jPanel3.setLayout(new java.awt.GridLayout(9, 1, 0, 5));

        tfFIO.setEditable(false);
        tfFIO.setMaximumSize(new java.awt.Dimension(200, 2147483647));
        jPanel3.add(tfFIO);

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        cbCardType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbCardType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCardTypeActionPerformed(evt);
            }
        });
        jPanel4.add(cbCardType);

        jPanel3.add(jPanel4);

        tfCode.setEditable(false);
        jPanel3.add(tfCode);

        tfMoney.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfMoneyActionPerformed(evt);
            }
        });
        jPanel3.add(tfMoney);

        jPanel9.setLayout(new java.awt.BorderLayout());

        dchCreated.setEnabled(false);
        dchCreated.setPreferredSize(new java.awt.Dimension(125, 19));
        jPanel9.add(dchCreated, java.awt.BorderLayout.WEST);

        jPanel3.add(jPanel9);

        jPanel7.setLayout(new java.awt.BorderLayout());

        dchExpired.setPreferredSize(new java.awt.Dimension(125, 19));
        dchExpired.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dchExpiredPropertyChange(evt);
            }
        });
        jPanel7.add(dchExpired, java.awt.BorderLayout.WEST);

        jPanel3.add(jPanel7);

        jPanel8.setLayout(new java.awt.BorderLayout());

        dchLastUsed.setEnabled(false);
        dchLastUsed.setPreferredSize(new java.awt.Dimension(125, 19));
        jPanel8.add(dchLastUsed, java.awt.BorderLayout.WEST);

        jPanel3.add(jPanel8);

        jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        btBlock.setText("заб/разб");
        btBlock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBlockActionPerformed(evt);
            }
        });
        jPanel10.add(btBlock);

        jPanel3.add(jPanel10);

        jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER);

        add(jPanel2, java.awt.BorderLayout.NORTH);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Клик на батоне Заблокировать/Разблокировать
     * @param evt
     */
private void btBlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBlockActionPerformed
    try {
        if (cardLocal.getBlocker() == null) {
            cardLocal.setBlocker(UserInfo.get().getCollaborator());
        } else {
            cardLocal.setBlocker(null);
        }
        updateScreenFields(cardLocal);
    } catch (ClipsException ex) {
        MessageBox.showException(ex);
    }
}//GEN-LAST:event_btBlockActionPerformed

    /**
     * Выбор типа карты
     * @param evt
     */
private void cbCardTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCardTypeActionPerformed
    try {
        if (cardLocal != null && cbCardType.getSelectedIndex() > -1) {
            cardLocal.setCardType((DirectoryDiscountCardTypeItem) cbCardType.getSelectedItem());
        }
    } catch (ClipsException ex) {
        MessageBox.showException(ex);
    }
}//GEN-LAST:event_cbCardTypeActionPerformed
    /**
     * Ентер в поле ввода суммы
     * @param evt
     */
private void tfMoneyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfMoneyActionPerformed
    try {
        dchCreated.requestFocus();
        updateScreenFields(cardLocal);
    } catch (ClipsException ex) {
        ex.printStackTrace();
    }
}//GEN-LAST:event_tfMoneyActionPerformed

    /**
     * установка срока действия
     * @param evt
     */
private void dchExpiredPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dchExpiredPropertyChange
}//GEN-LAST:event_dchExpiredPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btBlock;
    private javax.swing.JComboBox cbCardType;
    private org.infotechservice.ICalendar.components.ICDateChooser dchCreated;
    private org.infotechservice.ICalendar.components.ICDateChooser dchExpired;
    private org.infotechservice.ICalendar.components.ICDateChooser dchLastUsed;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JTextField tfBlock;
    private javax.swing.JTextField tfCode;
    private javax.swing.JTextField tfFIO;
    private javax.swing.JTextField tfMoney;
    // End of variables declaration//GEN-END:variables
    @Override
    public String getPageTitle() {
        return "Дисконтная карта";
    }

    @Override
    public boolean isDirty() {
        boolean res = (cardLocal == null) ? false : cardLocal.isDirty();
        return res;
    }

    @Override
    public void save() throws ClipsException {
        cardLocal.save1();
    }

    @Override
    public void restore() {
        try {
            cardLocal.restore();
            updateScreenFields(cardLocal);
        } catch (ClipsException ex) {
            MessageBox.showException(ex);
        }
    }

    @Override
    public DelegateLine2 getDelegate() {
        return cardLocal;
    }

}
TOP

Related Classes of clips.service.discount.card.PanelDiscountCard$NumberFilter

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.