OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 151 | Rev 177 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.core.sales.invoice.ui;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
import org.openconcerto.erp.core.finance.accounting.ui.ListeGestCommEltPanel;
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement;
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.GenerationResult;
import org.openconcerto.erp.core.finance.payment.element.SDDMessageSQLElement.IgnoreReason;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.ui.TextAreaTicketPanel;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.request.UpdateBuilder;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.ITableModel;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelColumnPath;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.ui.PanelFrame;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.TableSorter;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.i18n.Grammar_fr;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.TableColumn;

public class ListeDesVentesPanel extends JPanel {

    private ListeGestCommEltPanel listeFact;
    // private JButton buttonEnvoye, buttonRegle, buttonDupliquer;
    private JLabelBold textField = new JLabelBold("0");
    private JLabelBold textField2 = new JLabelBold("0");

    public ListeDesVentesPanel() {
        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(2, 2, 1, 2);
        c.fill = GridBagConstraints.BOTH;
        c.anchor = GridBagConstraints.NORTHWEST;
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 1;
        c.gridheight = 1;
        c.weightx = 1;
        c.weighty = 1;

        JTabbedPane tabbedPane = new JTabbedPane();

        final SQLElement elementVF = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
        // tab Vente facture
        final SQLElement eltFacture = elementVF;
        final SQLTableModelSourceOnline src = eltFacture.getTableSource(true);
        // Filter
        Where wPrev = new Where(eltFacture.getTable().getField("PREVISIONNELLE"), "=", Boolean.FALSE);
        if (src.getReq().getWhere() != null) {
            wPrev = wPrev.and(src.getReq().getWhere());
        }
        src.getReq().setWhere(wPrev);

        final ListeFactureRenderer rend = new ListeFactureRenderer();
        for (SQLTableModelColumn column : src.getColumns()) {
            if (column.getClass().isAssignableFrom(SQLTableModelColumnPath.class)) {
                ((SQLTableModelColumnPath) column).setEditable(false);
            }
            // FIXME Voir pour appliquer le renderer correctement
            if (!column.getName().startsWith("Avancement")) {
                column.setRenderer(rend);
            }
        }

        final SQLTableModelColumn dateEnvoiCol = src.getColumn(eltFacture.getTable().getField("DATE_ENVOI"));
            ((SQLTableModelColumnPath) dateEnvoiCol).setEditable(true);
        final SQLTableModelColumn dateReglCol = src.getColumn(eltFacture.getTable().getField("DATE_REGLEMENT"));
        if (dateReglCol != null)
            ((SQLTableModelColumnPath) dateReglCol).setEditable(true);

            // Edition des dates d'envois
            dateEnvoiCol.setColumnInstaller(new IClosure<TableColumn>() {
                @Override
                public void executeChecked(TableColumn columnDateEnvoi) {
                    final org.openconcerto.ui.table.TimestampTableCellEditor cellEditor = new org.openconcerto.ui.table.TimestampTableCellEditor();
                    cellEditor.setAllowNull(true);
                    columnDateEnvoi.setCellEditor(cellEditor);
                    columnDateEnvoi.setCellRenderer(new DateEnvoiRenderer());
                }
            });

        // Edition des dates de reglement
        if (dateReglCol != null) {
            dateReglCol.setColumnInstaller(new IClosure<TableColumn>() {

                @Override
                public void executeChecked(TableColumn columnDateReglement) {
                    final org.openconcerto.ui.table.TimestampTableCellEditor cellEditor = new org.openconcerto.ui.table.TimestampTableCellEditor();
                    cellEditor.setAllowNull(true);
                    columnDateReglement.setCellEditor(cellEditor);
                    columnDateReglement.setCellRenderer(new DateEnvoiRenderer());
                }
            });
        }

        src.getColumns().add(new SQLTableModelColumnPath(new FieldPath(new Path(eltFacture.getTable()).addForeignField(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME), "MessageIdentification")));

        this.listeFact = new ListeGestCommEltPanel(eltFacture, new IListe(src), true);
        final SDDMessageSQLElement sepaMsgElem = eltFacture.getDirectory().getElement(SDDMessageSQLElement.class);
        final String aMessageLabel = sepaMsgElem.getName().getVariant(Grammar_fr.INDEFINITE_ARTICLE_SINGULAR);
        this.listeFact.getListe().addIListeAction(new RowAction.PredicateRowAction(new AbstractAction("Générer " + aMessageLabel, null) {
            @Override
            public void actionPerformed(ActionEvent e) {
                final IListe l = IListe.get(e);
                final List<Integer> selectedIDs = l.getSelection().getSelectedIDs();
                // TODO dialog with label informing of the successful creation of message for n
                // invoices/n2 messages too far in the future/n3 messages with collection date
                // changed and having a button to open the file chooser
                new SwingWorker<GenerationResult, Void>() {
                    @Override
                    protected GenerationResult doInBackground() throws Exception {
                        return sepaMsgElem.generateXML(selectedIDs);
                    }

                    @Override
                    protected void done() {
                        final GenerationResult genRes;
                        try {
                            genRes = this.get();
                        } catch (Exception e) {
                            ExceptionHandler.handle(l, "Impossible de générer " + aMessageLabel, e);
                            return;
                        }
                        final int includedInvoicesCount = genRes.getIncludedInvoicesCount();
                        final Map<String, Object> tmMap = new HashMap<>();
                        tmMap.put("msgElem", sepaMsgElem.getName());
                        tmMap.put("invoiceElem", elementVF.getName());
                        tmMap.put("invoiceElemCount", includedInvoicesCount);
                        if (genRes.getDDInvoicesWithoutMessage().isEmpty()) {
                            JOptionPane.showMessageDialog(l, TM.getTM().trM("sddMessage.generation.noneNeeded", tmMap));
                        } else if (genRes.getIgnoredInvoices().isEmpty()) {
                            JOptionPane.showMessageDialog(l, TM.getTM().trM("sddMessage.generation.noneIgnored", tmMap));
                        } else {
                            final int futureCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.TOO_FAR_IN_FUTURE).size();
                            final int duplicateCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.DUPLICATE_MANDATE).size();
                            final int missingInfoCount = genRes.getIgnoredInvoices().getNonNull(IgnoreReason.MISSING_INFO).size();
                            tmMap.put("futureCount", futureCount);
                            tmMap.put("duplicateCount", duplicateCount);
                            tmMap.put("missingInfoCount", missingInfoCount);
                            final StringBuilder msg = new StringBuilder(256);
                            msg.append(TM.getTM().trM("sddMessage.generation.someIgnored", tmMap));
                            if (futureCount > 0) {
                                msg.append("\n- ");
                                msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.future", tmMap));
                            }
                            if (duplicateCount > 0) {
                                msg.append("\n- ");
                                msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.duplicateMandate", tmMap));
                            }
                            if (missingInfoCount > 0) {
                                msg.append("\n- ");
                                msg.append(TM.getTM().trM("sddMessage.generation.someIgnored.missingInfo", tmMap));
                            }
                            final int messageType = duplicateCount == 0 ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE;
                            JOptionPane.showMessageDialog(l, msg.toString(), null, messageType);
                        }
                        if (genRes.getInsertedMessage() != null) {
                            sepaMsgElem.exportXML(l, Collections.singletonList(genRes.getInsertedMessage()));
                        }
                    }
                }.execute();
            }
        }, false, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()));
        // TODO remove once we have a join with {SENT, OK, DEFINITIVE_ERROR, TRANSIENT_ERROR}
        this.listeFact.getListe().addIListeAction(new RowAction.PredicateRowAction(new AbstractAction("Prélever à nouveau", null) {
            @Override
            public void actionPerformed(ActionEvent e) {
                final IListe l = IListe.get(e);
                if (JOptionPane.showConfirmDialog(l, "Voulez-vous vraiment prélever à nouveau les factures sélectionnées ? Cette action est définitive.", "Prélever à nouveau",
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION)
                    return;
                final List<Integer> selectedIDs = l.getSelection().getSelectedIDs();
                final UpdateBuilder upd = new UpdateBuilder(l.getSource().getPrimaryTable());
                upd.setObject(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME, upd.getTable().getForeignTable(SaisieVenteFactureSQLElement.MESSAGE_FIELD_NAME).getUndefinedIDNumber());
                upd.setObject(SaisieVenteFactureSQLElement.END2END_FIELD_NAME, "");
                // don't allow to debit already payed invoices
                upd.setWhere(new Where(upd.getTable().getKey(), selectedIDs).and(Where.isNull(upd.getTable().getField("DATE_REGLEMENT"))));

                upd.getTable().getDBSystemRoot().getDataSource().execute(upd.asString());
                for (final Integer id : selectedIDs)
                    upd.getTable().fireTableModified(id, upd.getFieldsNames());
            }
        }, false, true).setPredicate(IListeEvent.getNonEmptySelectionPredicate()));
        this.listeFact.setOpaque(false);
        this.listeFact.getListe().setModificationAllowed(true);
        final JTable tableFact = this.listeFact.getListe().getJTable();
        final SQLTableModelColumn numeroCol = src.getColumn(eltFacture.getTable().getField("NUMERO"));
        ((TableSorter) tableFact.getModel()).setSortingStatus(src.getColumns().indexOf(numeroCol), TableSorter.ASCENDING);

        JPanel panelFacture = new JPanel(new GridBagLayout());
        GridBagConstraints cFacture = new DefaultGridBagConstraints();

        cFacture.gridy++;
        cFacture.gridx = 0;
        cFacture.weighty = 1;
        cFacture.weightx = 1;
        cFacture.gridwidth = GridBagConstraints.REMAINDER;
        cFacture.fill = GridBagConstraints.BOTH;
        panelFacture.add(this.listeFact, cFacture);

        List<SQLField> l = new ArrayList<SQLField>();
        if (this.listeFact.getListe().getSource().getColumn(eltFacture.getTable().getField("T_HA")) != null) {
            l.add(eltFacture.getTable().getField("T_HA"));
        }
        l.add(eltFacture.getTable().getField("T_HT"));
        l.add(eltFacture.getTable().getField("T_TTC"));
        final IListTotalPanel total = new IListTotalPanel(this.listeFact.getListe(), l);
        cFacture.weighty = 0;
        cFacture.fill = GridBagConstraints.NONE;
        cFacture.gridy++;
        cFacture.anchor = GridBagConstraints.EAST;
        total.setOpaque(false);
        panelFacture.add(total, cFacture);


        IListFilterDatePanel filterDate = new IListFilterDatePanel(this.listeFact.getListe(), eltFacture.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
        cFacture.weighty = 0;
        cFacture.fill = GridBagConstraints.HORIZONTAL;
        cFacture.gridy++;
        filterDate.setOpaque(false);
        panelFacture.add(filterDate, cFacture);
        tabbedPane.add("Ventes avec facture", panelFacture);

        PredicateRowAction actionRegle = new PredicateRowAction(new AbstractAction("Facture réglée") {

            @Override
            public void actionPerformed(ActionEvent e) {
                final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
                for (SQLRowAccessor sqlRowAccessor : selectedRows) {
                    final SQLRowValues rowVals = sqlRowAccessor.asRow().createEmptyUpdateRow();
                    rowVals.put("DATE_REGLEMENT", new Date());
                    try {
                        rowVals.update();
                    } catch (SQLException e1) {
                        ExceptionHandler.handle("Modification impossible", e1);
                    }
                }
            }
        }, true);
        actionRegle.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
        this.listeFact.getListe().addIListeAction(actionRegle);

        PredicateRowAction actionEnvoye = new PredicateRowAction(new AbstractAction("Facture envoyée") {

            @Override
            public void actionPerformed(ActionEvent e) {
                final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
                for (SQLRowAccessor sqlRowAccessor : selectedRows) {
                    final SQLRowValues rowVals = sqlRowAccessor.asRow().createEmptyUpdateRow();
                    rowVals.put("DATE_ENVOI", new Date());
                    try {
                        rowVals.update();
                    } catch (SQLException e1) {
                        ExceptionHandler.handle("Modification impossible", e1);
                    }
                }
            }
        }, true);
        actionEnvoye.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
        this.listeFact.getListe().addIListeAction(actionEnvoye);


            {
                // Tab Vente caisse
                ListeViewPanel panelTicket = new ListeViewPanel(Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE")) {
                    @Override
                    protected void handleAction(JButton source, ActionEvent evt) {
                        if (source == this.buttonModifier) {
                            POSConfiguration posConf = POSConfiguration.getInstance();
                            try {
                                if (posConf == null)
                                    posConf = POSConfiguration.setInstance();
                            } catch (Exception e) {
                                ExceptionHandler.handle(source, "Impossible d'initialiser la configuration de la caisse", e);
                                return;
                            }
                            new PanelFrame(new TextAreaTicketPanel(posConf, this.getListe().fetchSelectedRow()), "Ticket").setVisible(true);
                        } else {
                            super.handleAction(source, evt);
                        }
                    }
                };

                JPanel panel = new JPanel(new GridBagLayout());
                GridBagConstraints cc = new DefaultGridBagConstraints();
                cc.weightx = 1;
                cc.weighty = 1;
                cc.fill = GridBagConstraints.BOTH;
                panel.add(panelTicket, cc);

                final List<SQLField> l2 = new ArrayList<SQLField>();
                l2.add(panelTicket.getElement().getTable().getField("TOTAL_HT"));
                l2.add(panelTicket.getElement().getTable().getField("TOTAL_TTC"));
                final IListTotalPanel total2 = new IListTotalPanel(panelTicket.getListe(), l2);
                cc.weighty = 0;
                cc.fill = GridBagConstraints.NONE;
                cc.gridy++;
                cc.anchor = GridBagConstraints.EAST;
                total2.setOpaque(false);
                panel.add(total2, cc);

                IListFilterDatePanel filterDate2 = new IListFilterDatePanel(panelTicket.getListe(), panelTicket.getElement().getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
                cc.weighty = 0;
                cc.fill = GridBagConstraints.HORIZONTAL;
                cc.gridy++;
                filterDate2.setOpaque(false);
                panel.add(filterDate2, cc);

                tabbedPane.add("Ventes caisse", panel);

            }
            // Tab Vente comptoir
            {
                final ListeGestCommEltPanel listeVC = new ListeGestCommEltPanel(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_COMPTOIR"), true);
                listeVC.getListe().setModificationAllowed(false);
                listeVC.setOpaque(false);

                final JTable table = listeVC.getListe().getJTable();
                for (int i = 0; i < table.getColumnCount(); i++) {
                    if (table.getColumnClass(i) == Long.class || table.getColumnClass(i) == BigInteger.class) {
                        table.getColumnModel().getColumn(i).setCellRenderer(rend);
                    }
                }

                JPanel panelComptoir = new JPanel(new GridBagLayout());
                GridBagConstraints cc = new DefaultGridBagConstraints();
                cc.weightx = 1;
                cc.weighty = 1;
                cc.fill = GridBagConstraints.BOTH;
                panelComptoir.add(listeVC, cc);

                final List<SQLField> l2 = new ArrayList<SQLField>();
                l2.add(listeVC.getElement().getTable().getField("MONTANT_HT"));
                l2.add(listeVC.getElement().getTable().getField("MONTANT_TTC"));
                final IListTotalPanel total2 = new IListTotalPanel(listeVC.getListe(), l2);
                cc.weighty = 0;
                cc.fill = GridBagConstraints.NONE;
                cc.gridy++;
                cc.anchor = GridBagConstraints.EAST;
                total2.setOpaque(false);
                panelComptoir.add(total2, cc);

                IListFilterDatePanel filterDate2 = new IListFilterDatePanel(listeVC.getListe(), listeVC.getElement().getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());
                cc.weighty = 0;
                cc.fill = GridBagConstraints.HORIZONTAL;
                cc.gridy++;
                filterDate2.setOpaque(false);
                panelComptoir.add(filterDate2, cc);

                tabbedPane.add("Ventes comptoir", panelComptoir);
            }
        this.add(tabbedPane, c);
    }

}