Package clips.administrator.expenditure

Source Code of clips.administrator.expenditure.PanelExpenTable

/*
* PanelExpenTable.java
*
* Created on 27 Март 2008 г., 16:32
*/
package clips.administrator.expenditure;

import clips.delegate.directory.complex.DirectoryExpenditureType;
import clips.delegate.directory.complex.DirectoryExpenditureTypeItem;
import cli_fmw.delegate.directory.complex.DirectoryLocator;
import clips.delegate.expenditure.ExpenditureItemData;
import clips.delegate.expenditure.ExpenditureLocal;
import clips.delegate.directory.filtered.DirectoryServiceItem;
import cli_fmw.delegate.DelegateLine2;
import clips.delegate.service.SerRenLocal;
import cli_fmw.directory.dialogs.DirectoryDialogDefault;
import cli_fmw.main.Lockable;
import cli_fmw.main.PageContainer;
import cli_fmw.main.PageGeneric;
import cli_fmw.main.Persistentable;
import cli_fmw.utils.ErrorModeListener;
import cli_fmw.utils.Selector;
import cli_fmw.utils.SelectorEditable;
import cli_fmw.utils.MessageBox;
import cli_fmw.utils.ModalDialog;
import cli_fmw.main.ClipsException;
import cli_fmw.utils.table_config_states.StateSaver;
import cli_fmw.utils.table_config_states.TableState;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableModel;

/**
* Панель, отображающая в таблице данные по расходу материалов
* @author  petr
*/
public class PanelExpenTable extends PageGeneric
        implements Persistentable, Lockable {

    private SerRenLocal serRenLocal;
    private DirectoryServiceItem service;
    private boolean inEditor;
    private ExpenditureLocal expenditureLocal;
    private SelectorEditable<ExpenditureItemData> items;
    private boolean editable;
           
    /**
     * этот конструктор предполагается юзать в редакторе
     * право на редактирование имеют:
     * администратор
     * @param expenDefLoc - делегат расхода по дефолту
     * @param container - контейнер
     * @throws cli_fmw.delegate.exception.ClipsException
     */
    public PanelExpenTable(DirectoryServiceItem service, PageContainer container) throws ClipsException {
        super(container);
        initComponents();
       
        expenditureLocal = new ExpenditureLocal();       
        editable = expenditureLocal.canModify();
       
        if (editable) {
            removeButton.setEnabled(true);
            addButton.setEnabled(true);
        }
        this.service = service;
        expenditureLocal.addContentStateListener(container);

        items = expenditureLocal.getExpenditureList(service);

        resetTable();

        // Вешаем слушатель на панель, при изменении размеров панели будет меняться ширина столбцов таблицы
        inEditor = true;
    resizeTableColums();
    StateSaver.attachTo(this);
    }

    /**
     * этот конструктор предполагается юзать из панели врача,
     * право на редактирование имеют:
     * администратор, дохтур (только при оказании услуги)
   * @param serRen - оказаная услуга
     * @param container - контейнер
     * @throws ClipsException
     */
    public PanelExpenTable(SerRenLocal serRen, PageContainer container) throws ClipsException {
        super(container);
        initComponents();
        serRenLocal = serRen;
       
        editable = serRen.canModify();
        //можно редактировать то включаем кнопки
        if (editable) {
            removeButton.setEnabled(true);
            addButton.setEnabled(true);
        }
       
        serRenLocal.addContentStateListener(container);
        items = serRenLocal.getExpenditureList();
        if (items.size() == 0){//если данных о расходе в серрене нет знач используем дефолтный расход
            expenditureLocal = new ExpenditureLocal();
            items = expenditureLocal.getExpenditureList(serRenLocal.getService());
        }
        resetTable();
    resizeTableColums();
    StateSaver.attachTo(this);
    }

    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblExpenditure = new cli_fmw.utils.sorted_table.SortedTable();

        setLayout(new java.awt.BorderLayout(0, 5));

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

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

        addButton.setText("Добавить");
        addButton.setEnabled(false);
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });
        jPanel1.add(addButton);

        removeButton.setText("Удалить");
        removeButton.setEnabled(false);
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });
        jPanel1.add(removeButton);

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

        add(jPanel2, java.awt.BorderLayout.SOUTH);

        jScrollPane1.setViewportView(tblExpenditure);

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

    /**
     * кнопка добавить материал
     * @param evt
     */
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        if (!inEditor){
            if (!trySetRealState()) return;
        }
            try {
                DirectoryExpenditureType det
                        = (DirectoryExpenditureType) DirectoryLocator.getDirectory(DirectoryExpenditureType.class, false);

                DirectoryDialogDefault dialogDefault = new DirectoryDialogDefault(true, null, "\\", det);
                dialogDefault.setVisible(true);
                if (dialogDefault.getDlgResult() == ModalDialog.DLG_OK){
                    Selector s = dialogDefault.getSelectedItems();
                    for (int i = 0; i < s.size(); i++) {
                        ExpenditureItemData eil;
                        if (serRenLocal != null) {
                            eil = new ExpenditureItemData(serRenLocal);
                        } else {
                            eil = new ExpenditureItemData(service);
                        }
                        DirectoryExpenditureTypeItem type = (DirectoryExpenditureTypeItem) s.get(i);
                        eil.setType(type);
                        items.append(eil);
                        resetTable();
                    }
                }

            } catch (ClipsException ex) {
                MessageBox.showException(ex);
            }
       
}//GEN-LAST:event_addButtonActionPerformed

    /**
     * кнопка удалить материал
     * @param evt
     */
    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        if (tblExpenditure.getSelectedRowCount() > 0) {
        if (!inEditor){
            if (!trySetRealState()) return;
        }
                int[] sel = tblExpenditure.getSelectedRowsSorted();
                for (int i = sel.length - 1; i >= 0; i--) {
                    items.remove(sel[i]);
                }
                resetTable();
        }
}//GEN-LAST:event_removeButtonActionPerformed

    public TableModel getTableModel() {
        return tblExpenditure.getModel();
    }
   
    /**
     * Обновление таблицы
     */
    private void resetTable() {
        //строим модель на основе обновлённого кеша
        TableModelExpenditureEdit model = new
                TableModelExpenditureEdit(items, editable);
        model.addTableModelListener(new javax.swing.event.TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent arg0) {
                if (trySetRealState()) {//пробуем подменить делегат
                    resetTable();
                }
            }
        });

        tblExpenditure.setModel(model); //обновляем таблицу
        tblExpenditure.revalidate();
        tblExpenditure.repaint();
        getContainer().contentStateChanged();
    }

    /**
     * Подменяет расход с дефолта на реальный
     * @return истина, если была подмена
     */
    private boolean trySetRealState() {
        try {
            if (inEditor) {
                return false;
            }

            if (serRenLocal != null && serRenLocal.getExpenditureList().size() > 0) {
                return true;
            }

            if (editable && expenditureLocal != null && serRenLocal != null) {
                if (MessageBox.showConfirmYesNo(MessageBox.C_CHANGE_EXPENDITURE) == MessageBox.ANSWER_YES) {
                    items = makeCopyOfDefaultExpenditure(serRenLocal.getService());
                    return true;
                }else{
                    ((TableModelExpenditureEdit) tblExpenditure.getModel()).recoverChangedValue();
                }
            } else {
                //may be add code here
            }
        } catch (ClipsException ex) {
            MessageBox.showException(ex);
            ((TableModelExpenditureEdit) tblExpenditure.getModel()).recoverChangedValue();
        }
        return false;
    }

    /**
     * Создаёт реальный расход на основе дефолтного
     * @param expDefLoc0
     */
    private SelectorEditable<ExpenditureItemData> makeCopyOfDefaultExpenditure(DirectoryServiceItem service)
            throws ClipsException {
        SelectorEditable<ExpenditureItemData> defaultList = null;
        if (expenditureLocal != null){
            defaultList = expenditureLocal.getExpenditureList(service);
        }
       
        SelectorEditable<ExpenditureItemData> list = serRenLocal.getExpenditureList();
        if (list.size() != 0){
            throw new RuntimeException("Заменить реальный расход на новый можно только если он пустой");
        }
        if(defaultList != null) {
            for (int i = 0; i < defaultList.size(); i++) {
                ExpenditureItemData item = defaultList.get(i);
                ExpenditureItemData newItem = new ExpenditureItemData(service);

                newItem.setQuantity(item.getQuantity());
                newItem.setType(item.getType());
                list.append(newItem);
            }
        }
       
        return list;
    }   
   
    /**
     * Установка ширины столбцов
     */
    private void resizeTableColums() {
    TableState          state = new TableState();
    state.setPreferredWidth(TableModelExpenditureEdit.COL_EXPEN_TYPE,    3);
    state.setPreferredWidth(TableModelExpenditureEdit.COL_QUANTITY,      1);
    state.setPreferredWidth(TableModelExpenditureEdit.COL_METRIC,      1);
      StateSaver.setDefaultState(this, tblExpenditure, state);
    }

    @Override
    public String getPageTitle() {
        return "расход материалов";
    }

    @Override
    public boolean isDirty() {

        if (serRenLocal == null) {
//            for (int  i= 0; i< items.size();i++){
//                try {
//                    if (!items.get(i).equals(originals.get(items.get(i)))) {
//                        return true;
//                    }
//                } catch (ClipsException ex) {
//                    MessageBox.showNonClipsFatalException(ex);
//                }
//            }
            return expenditureLocal.isDirty();
        } else {
            return serRenLocal.isDirty();
        }
    }

    @Override
    public void save() throws ClipsException {

        if (serRenLocal == null) {
            expenditureLocal.save1();
        } else {
            serRenLocal.save1();
        }
       
    }

    @Override
    public void restore() {
         if (serRenLocal == null) {
            expenditureLocal.restore();
        } else  {
            serRenLocal.restore();
            if (expenditureLocal != null)
                expenditureLocal.restore();
        }
        resetTable();
    }

    @Override
    public void lock() {
        tblExpenditure.setEnabled(false);
        removeButton.setEnabled(false);
        addButton.setEnabled(false);
        tblExpenditure.removeMouseListener(ErrorModeListener.errorModeListener);
        removeButton.removeMouseListener(ErrorModeListener.errorModeListener);
        addButton.removeMouseListener(ErrorModeListener.errorModeListener);
        jScrollPane1.removeMouseListener(ErrorModeListener.errorModeListener);
        tblExpenditure.addMouseListener(ErrorModeListener.errorModeListener);
        removeButton.addMouseListener(ErrorModeListener.errorModeListener);
        addButton.addMouseListener(ErrorModeListener.errorModeListener);
        jScrollPane1.addMouseListener(ErrorModeListener.errorModeListener);
    }
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton removeButton;
    private cli_fmw.utils.sorted_table.SortedTable tblExpenditure;
    // End of variables declaration//GEN-END:variables

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

}
TOP

Related Classes of clips.administrator.expenditure.PanelExpenTable

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.