OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | 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.pos.ui;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.sales.pos.POSConfiguration;
import org.openconcerto.erp.core.sales.pos.model.Client;
import org.openconcerto.erp.core.sales.pos.model.DBState;
import org.openconcerto.erp.core.sales.pos.model.ReceiptCode;
import org.openconcerto.erp.core.sales.pos.model.RegisterDB;
import org.openconcerto.erp.core.sales.pos.model.RegisterFiles;
import org.openconcerto.erp.core.sales.pos.model.RegisterLog;
import org.openconcerto.erp.core.sales.pos.model.RegisterState;
import org.openconcerto.erp.core.sales.pos.model.RegisterState.Status;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.erp.core.sales.pos.model.TicketItem;
import org.openconcerto.erp.utils.TM;
import org.openconcerto.sql.PropsConfiguration;
import org.openconcerto.sql.RemoteShell;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.sqlobject.ElementComboBox;
import org.openconcerto.utils.ClassPathLoader;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.cc.ExnTransformer;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;

import org.jdom2.JDOMException;

public class CaisseFrame extends JFrame {
    private final POSConfiguration posConf;
    private final ComptaPropsConfiguration conf;
    private final RegisterFiles files;
    private final RegisterDB registerDB;
    final CaissePanel mainPanel;

    CaisseFrame(final POSConfiguration posConf, final ComptaPropsConfiguration conf, final RegisterFiles files, final RegisterDB registerDB) throws Exception {
        this.posConf = posConf;
        this.conf = conf;
        this.files = files;
        this.registerDB = registerDB;
        this.mainPanel = new CaissePanel(this);
        setContentPane(mainPanel);
        setFocusable(true);
    }

    public final POSConfiguration getPOSConf() {
        return this.posConf;
    }

    public final ComptaPropsConfiguration getConf() {
        return this.conf;
    }

    public final RegisterFiles getFiles() {
        return this.files;
    }

    public final RegisterDB getDB() {
        return this.registerDB;
    }

    public static void main(String[] args) {
        System.setProperty(SQLRowAccessor.ACCESS_DB_IF_NEEDED_PROP, "true");
        try {
            System.out.println("Lancement du module de caisse");
            ToolTipManager.sharedInstance().setInitialDelay(0);
            RemoteShell.startDefaultInstance(null, null);

            System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
            System.setProperty(SQLBase.ALLOW_OBJECT_REMOVAL, "true");

            ExceptionHandler.setForceUI(true);
            ExceptionHandler.setForumURL("http://www.openconcerto.org/forum");
            ExceptionHandler.setThrowableHandler(Gestion.createDefaultThrowableHandler());
            // SpeedUp Linux
            System.setProperty("sun.java2d.pmoffscreen", "false");
            System.setProperty(SQLBase.STRUCTURE_USE_XML, "true");
            System.setProperty(PropsConfiguration.REDIRECT_TO_FILE, "true");
            final POSConfiguration posConf = POSConfiguration.setInstance();
            if (posConf.isUsingJPos()) {
                ClassPathLoader c = ClassPathLoader.getInstance();
                try {
                    final List<String> posDirectories = posConf.getJPosDirectories();
                    for (String posDirectory : posDirectories) {
                        if (posDirectory != null && !posDirectory.trim().isEmpty()) {
                            c.addJarFromDirectory(new File(posDirectory.trim()));
                        }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                c.load();

            }
            final ComptaPropsConfiguration conf = posConf.createConnexion();

            final int userID = posConf.getUserID();
            final int posID = posConf.getPosID();
            final RegisterFiles registerFiles = new RegisterFiles(posConf.getRootDir(), true, posConf.getPosID());
            final RegisterDB registerDB = new RegisterDB(conf.getDirectory(), conf.getProductInfo(), posConf.getPosID());
            // check if register exists
            final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(new SQLRowValues(registerDB.getRegisterTable()));
            if (fetcher.fetchOne(posID) == null) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(null, TM.tr("register.missing", posID), TM.tr("register.missing.title"), JOptionPane.ERROR_MESSAGE);
                });
                posConf.closeConnexion();
                return;
            }
            // check before changing any state
            final boolean quit = registerDB.fetchRegisterState().checkIfMoved();
            if (quit) {
                quit(posConf);
                return;
            }

            final Logger logger = POSConfiguration.getLogger();
            final RegisterState reconciledState;
            try {
                reconciledState = registerFiles.doWithLock(new ExnTransformer<RegisterFiles, RegisterState, Exception>() {
                    @Override
                    public RegisterState transformChecked(RegisterFiles input) throws Exception {
                        return reconcileFSandDB(posConf, conf.getDirectory(), input, registerDB);
                    }
                });
            } catch (ReconcileException re) {
                logger.log(Level.WARNING, "States couldn’t be reconciled, local : " + re.getLocalState() + ", remote : " + re.getRemoteState(), re);
                final String generalMsg;
                boolean onlyOptionPane = false;
                if (re instanceof OutsideMeddlingException) {
                    generalMsg = TM.tr("register.notReconciled.outsideMeddling") + '\n';
                    onlyOptionPane = true;
                } else if (re instanceof ResumeException) {
                    generalMsg = TM.tr("register.notReconciled.resumeFailed") + '\n';
                } else {
                    generalMsg = "";
                }
                final String message = TM.getTM().trM("register.notReconciled." + re.getTranslationKey(), "localDate", re.getLocalState().copyDate(), "remoteDate", re.getRemoteState().copyDate());
                if (onlyOptionPane) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(null, generalMsg + message, TM.tr("register.notReconciled.title"), JOptionPane.ERROR_MESSAGE);
                    });
                } else {
                    ExceptionHandler.handle(generalMsg + message, re);
                }
                // ATTN this calls ComptaPropsConfiguration.tearDownLogging(), so even syserr is
                // closed.
                posConf.closeConnexion();
                return;
            } catch (Exception e) {
                throw new IOException("Couldn't reconcile local and remote state", e);
            }
            logger.log(Level.INFO, "FS and DB states reconciled : {0}", reconciledState);

            System.setProperty("awt.useSystemAAFontSettings", "on");
            System.setProperty("swing.aatext", "true");
            System.setProperty(ElementComboBox.CAN_MODIFY, "true");

            RegisterState state = reconciledState;
            if (reconciledState.getStatus() == Status.CLOSED) {
                final FutureTask<Boolean> askUserCallable = new FutureTask<>(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        final int ans = JOptionPane.showConfirmDialog(null, "La caisse n’est pas ouverte, voulez-vous l’ouvrir ?", "Caisse fermée", JOptionPane.YES_NO_OPTION);
                        return ans == JOptionPane.YES_OPTION;

                    }
                });
                SwingUtilities.invokeLater(askUserCallable);
                final boolean userAgreed = askUserCallable.get();
                if (userAgreed) {
                    final RegisterLog newLog = registerFiles.open(userID, registerDB);
                    state = newLog.getRegisterState();
                }
            }
            if (state.getStatus() != Status.OPEN) {
                logger.log(Level.FINE, "State not open ({0}), exiting", state);
                posConf.closeConnexion();
                return;
            }
            logger.log(Level.INFO, "FS and DB states open, opening UI");

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {

                    try {
                        CaisseFrame f = new CaisseFrame(posConf, conf, registerFiles, registerDB);
                        f.setUndecorated(true);
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                        f.pack();
                        if (System.getProperty("os.name").toLowerCase().startsWith("mac os x")) {
                            f.setLocation(0, 24);
                        } else {
                            f.setLocation(0, 0);
                        }
                        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                        if (posConf.getScreenWidth() > 0 && posConf.getScreenHeight() > 0) {
                            f.setSize(new Dimension(posConf.getScreenWidth() - f.getX(), posConf.getScreenHeight() - f.getY()));
                        } else {
                            f.setSize(new Dimension(screenSize.getSize().width - f.getX(), screenSize.getSize().height - f.getY()));
                        }
                        System.out.println("Affichage de l'interface");
                        f.setVisible(true);
                        if (screenSize.getWidth() < 1024 || screenSize.getHeight() < 720) {
                            JOptionPane.showMessageDialog(f,
                                    "La résolution de votre écran est trop faible.\nLa largeur doit être au minium de 1024 pixels.\nLa hauteur doit être au minium de 720 pixels.");
                        }
                    } catch (Throwable e) {
                        // Catch throwable to be able to see NoClassDefFound and other hard issues
                        ExceptionHandler.handle("Erreur d'initialisation de la caisse (main)", e);
                    }

                }
            });
        } catch (Throwable e) {
            // Catch throwable to be able to see NoClassDefFound and other hard issues
            ExceptionHandler.handle("Erreur d'initialisation de la caisse", e);
        }
    }

    public static class ReconcileException extends IllegalStateException {
        private RegisterState localState, remoteState;
        private final String translationKey;

        protected ReconcileException(final String msg, final String key) {
            this(msg, key, null);
        }

        protected ReconcileException(final String msg, final String key, final Throwable cause) {
            super(Objects.requireNonNull(msg, "message"), cause);
            this.translationKey = Objects.requireNonNull(key, "translation key");
        }

        public final RegisterState getLocalState() {
            return this.localState;
        }

        public final RegisterState getRemoteState() {
            return this.remoteState;
        }

        public final String getTranslationKey() {
            return this.translationKey;
        }

        protected final ReconcileException init(final RegisterState localState, final RegisterState remoteState) {
            this.localState = Objects.requireNonNull(localState, "local state");
            this.remoteState = Objects.requireNonNull(remoteState, "remote state");
            return this;
        }
    }

    // the FS and/or DB states were modified outside of this software.
    public static final class OutsideMeddlingException extends ReconcileException {
        protected OutsideMeddlingException(final String msg, final String key) {
            super(msg, key);
        }
    }

    // the opening or closure was interrupted, the process was resumed but it failed.
    public static final class ResumeException extends ReconcileException {
        protected ResumeException(final String msg, final String key, final Throwable cause) {
            super(msg, key, Objects.requireNonNull(cause, "missing cause"));
        }
    }

    /*
     * List of translations keys.
     */
    private static final String unknownTK = "unknown";
    // localOpen
    private static final String open_datesMismatch = "open.datesMismatch";
    private static final String localOpen_remoteClosed = "localOpen_remoteClosed";
    private static final String localOpen_remoteMissing = "localOpen_remoteMissing";
    // remoteOpen
    private static final String localMissing_remoteReopen = "localMissing_remoteReopen";
    private static final String localOpenFailed_remoteOpen = "localOpenFailed_remoteOpen";
    private static final String localClosed_remoteCloseFailed = "localClosed_remoteCloseFailed";
    private static final String localClosed_remoteOpen_datesMismatch = "localClosed_remoteOpen.datesMismatch";
    // both closed
    private static final String localMissing_remoteClosed = "localMissing_remoteClosed";
    private static final String closed_datesMismatch = "closed.datesMismatch";
    private static final String localClosed_remoteMissing = "localClosed_remoteMissing";

    private static RegisterState reconcileFSandDB(final POSConfiguration posConf, final SQLElementDirectory dir, final RegisterFiles files, final RegisterDB registerDB)
            throws IOException, JDOMException, ParseException, SQLException {

        // *** find local and remote states
        final RegisterLog lastLog = files.getLastLog();
        POSConfiguration.getLogger().log(Level.CONFIG, "Found last log {0}", lastLog);

        RegisterState localState;
        if (lastLog == null) {
            final List<File> remainingReceipts = ReceiptCode.getReceiptsToImport(files.getPosID());
            localState = new RegisterState(remainingReceipts.isEmpty() ? Status.CLOSED : Status.OBSOLETE, null);
        } else {
            localState = lastLog.getRegisterState();
        }
        POSConfiguration.getLogger().log(Level.CONFIG, "FS state {0}", localState);

        final DBState fetchedState = registerDB.fetchRegisterState();
        RegisterState remoteState = fetchedState.getRegisterState();
        POSConfiguration.getLogger().log(Level.CONFIG, "DB state {0}", fetchedState);

        // *** import remaining obsolete receipts
        if (localState.getStatus() == Status.OBSOLETE) {
            if (remoteState.hasDate())
                throw new IllegalStateException("There remains obsolete receipts but DB can no longer import them : " + remoteState);
            final List<Ticket> allTickets = posConf.allTickets();
            POSConfiguration.getLogger().log(Level.INFO, "{0} obsolete receipt(s) will be stored in the DB", allTickets.size());
            posConf.commitAll(allTickets);
            final List<File> remainingReceipts = ReceiptCode.getReceiptsToImport(files.getPosID());
            if (!remainingReceipts.isEmpty())
                throw new IllegalStateException("Not all obsolete receipts could be imported : " + remainingReceipts);
            localState = new RegisterState(Status.CLOSED, null);
            POSConfiguration.getLogger().log(Level.FINE, "All obsolete receipts have been stored in the DB");
        }
        final EnumSet<Status> validStatus = EnumSet.of(Status.OPEN, Status.CLOSED);
        if (!validStatus.contains(localState.getStatus()))
            throw new IllegalStateException("Unexpected local status :" + localState);
        if (!validStatus.contains(remoteState.getStatus()))
            throw new IllegalStateException("Unexpected remote status :" + remoteState);

        // *** reconcile if possible
        if (!localState.equals(remoteState)) {
            POSConfiguration.getLogger().log(Level.INFO, "Different FS and DB state, will try to reconcile\nFS " + localState + " with\nDB " + remoteState);
            final int userID = posConf.getUserID();

            // OK because of the check above
            final boolean localOpen = localState.getStatus() == Status.OPEN;
            final boolean remoteOpen = remoteState.getStatus() == Status.OPEN;
            // Time line
            // 0
            // Open DB
            // 1
            // Open Local
            // 2
            // Create tickets...
            // 3
            // Close Local
            // 4
            // Close DB
            // 5
            // Open DB
            // 6
            // Open Local
            // 7
            try {
                if (localOpen) {
                    if (remoteOpen) {
                        throw new OutsideMeddlingException("Both open with but with different dates", open_datesMismatch);
                    } else {
                        // DB is at 0 or 5, local is at 2
                        throw new OutsideMeddlingException("local is open but the DB isn't", remoteState.hasDate() ? localOpen_remoteClosed : localOpen_remoteMissing);
                    }
                } else if (remoteOpen) {
                    assert remoteState.hasDate() : "Remote state open without date : " + remoteState;
                    final SQLRowValues lastClosure = fetchedState.getLastClosureEntry();
                    final java.util.Date lastClosureDate = lastClosure == null ? null : lastClosure.getDate("DATE").getTime();
                    if (!localState.hasDate()) {
                        // at 1
                        // MAYBE allow it for new install, for now the receipts must be copied
                        // over
                        if (lastClosureDate != null)
                            throw new OutsideMeddlingException("DB was closed and now open, but local log is missing", localMissing_remoteReopen);
                        try {
                            localState = files.open(userID, fetchedState).getRegisterState();
                        } catch (Exception e) {
                            throw new ResumeException("The local opening (following the already open DB) failed", localOpenFailed_remoteOpen, e);
                        }
                    } else if (remoteState.compareDateTo(lastLog.getFirstRegisterEvent().getDate()) == 0) {
                        // at 4
                        try {
                            remoteState = registerDB.close(posConf, files.getLastLog()).getRegisterState();
                        } catch (Exception e) {
                            throw new ResumeException("The closure of the DB (following the already closed local) failed", localClosed_remoteCloseFailed, e);
                        }
                    } else if (lastClosureDate != null && localState.compareDateTo(lastClosureDate) == 0) {
                        // at 6, TODO factor with above
                        try {
                            localState = files.open(userID, fetchedState).getRegisterState();
                        } catch (Exception e) {
                            throw new ResumeException("The local opening (following the already open DB) failed", localOpenFailed_remoteOpen, e);
                        }
                    } else {
                        // DB is at 1, local is between 4 and 6
                        throw new OutsideMeddlingException("DB was opened for a different date", localClosed_remoteOpen_datesMismatch);
                    }
                } else {
                    assert !localOpen && !remoteOpen;
                    if (!localState.hasDate()) {
                        assert remoteState.hasDate() : "Both closed with no dates, but not equal";
                        // DB is at 5, local is at 0
                        // MAYBE allow it for new install, for now the receipts must be copied
                        // over
                        throw new OutsideMeddlingException("DB was opened and closed, but local log is missing", localMissing_remoteClosed);
                    } else if (remoteState.hasDate()) {
                        // DB is at 5, local is at 5 but not for the same day
                        assert remoteState.compareDateTo(localState) != 0 : "Both closed with equal dates, but not equal";
                        throw new OutsideMeddlingException("DB was opened and closed for a different date", closed_datesMismatch);
                    } else {
                        // DB is at 0, local is between 4 and 6
                        throw new OutsideMeddlingException("DB was never opened but local was closed", localClosed_remoteMissing);
                    }
                }
            } catch (ReconcileException e) {
                throw e.init(localState, remoteState);
            } catch (Exception e) {
                throw new ReconcileException("Unknown exception", unknownTK, e).init(localState, remoteState);
            }
        }
        if (!remoteState.equals(localState))
            throw new IllegalStateException("Unexpected state");
        return remoteState;
    }

    static public void quit(final POSConfiguration posConf) {
        POSConfiguration.getLogger().log(Level.INFO, "User exit");
        posConf.closeConnexion();
        Frame[] l = Frame.getFrames();
        for (int i = 0; i < l.length; i++) {
            Frame f = l[i];
            System.err.println(f.getName() + " " + f + " Displayable: " + f.isDisplayable() + " Valid: " + f.isValid() + " Active: " + f.isActive());
        }
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for (Thread thread : threadSet) {
            if (!thread.isDaemon()) {
                System.err.println(thread.getName() + " " + thread.getId() + " not daemon");
            }
        }
    }

    @Override
    public void dispose() {
        quit(this.posConf);
        // Fermeture
        this.getControler().setLCD("   CAISSE FERMEE    ", "", 0);
        super.dispose();
    }

    public void showMenu() {
        System.out.println("CaisseFrame.showMenu()");
        final CaisseMenuPanel panel = new CaisseMenuPanel(this);
        showPanel(panel);
        this.getControler().setLCD("OpenConcerto", "Menu", 0);

    }

    public void showPanel(final JPanel panel) {
        this.invalidate();
        final int x = (getWidth() - panel.getPreferredSize().width) / 2;
        final int y = 100;
        final POSGlassPane glassPane2 = new POSGlassPane(panel, x, y) {
            @Override
            public void mousePressed(MouseEvent e) {
                Point containerPoint = SwingUtilities.convertPoint(this, e.getPoint(), panel);
                if (containerPoint.x < 0 || containerPoint.x > panel.getWidth() || containerPoint.y < 0 || containerPoint.y > panel.getHeight()) {
                    setGlassPane(new JPanel());
                    getGlassPane().setVisible(false);
                }
                super.mousePressed(e);
            }

        };
        this.setGlassPane(glassPane2);
        this.getGlassPane().setVisible(true);
        this.validate();
        this.repaint();
    }

    public void showPriceEditor(TicketItem item, CaisseControler caisseControler) {
        getControler().disableBarcodeReader();
        System.out.println("CaisseFrame.showPriceEditor()");
        this.invalidate();
        final PriceEditorPanel panel = new PriceEditorPanel(this, item);

        final POSGlassPane glassPane2 = new POSGlassPane(panel, (getWidth() - panel.getPreferredSize().width) / 2, 100) {
            @Override
            public void mousePressed(MouseEvent e) {
                Point containerPoint = SwingUtilities.convertPoint(this, e.getPoint(), panel);
                if (containerPoint.x < 0 || containerPoint.x > panel.getWidth() || containerPoint.y < 0 || containerPoint.y > panel.getHeight()) {
                    setGlassPane(new JPanel());
                    getGlassPane().setVisible(false);
                    getControler().enableBarcodeReader();

                }
                super.mousePressed(e);
            }

        };
        this.setGlassPane(glassPane2);
        this.getGlassPane().setVisible(true);
        this.validate();
        this.repaint();

    }

    public void showCaisse() {
        getControler().enableBarcodeReader();
        setGlassPane(new JPanel());
        getGlassPane().setVisible(false);

        System.out.println("CaisseFrame.showCaisse()");
        this.setContentPane(this.mainPanel);
        this.getControler().setLCD("OpenConcerto", "Caisse", 0);
        this.getControler().setLCDDefaultDisplay(5);
    }

    public void showTickets(Ticket t) {
        System.out.println("CaisseFrame.showMenu()");
        final ListeDesTicketsPanel panel = new ListeDesTicketsPanel(this);
        panel.setSelectedTicket(t);
        this.setContentPane(panel);
    }

    public CaisseControler getControler() {
        return this.mainPanel.getControler();
    }

    public void showClients() {
        System.out.println("CaisseFrame.showClients()");
        final ListeDesClientsPanel panel = new ListeDesClientsPanel(this);
        this.setContentPane(panel);
    }

    public void setClient(Client client) {
        System.err.println("CaisseFrame.setClient() " + client.getFullName());
        this.getControler().setClient(client);

    }

    @Override
    public void setContentPane(Container contentPane) {
        this.invalidate();
        setGlassPane(new JPanel());
        getGlassPane().setVisible(false);
        super.setContentPane(contentPane);
        this.validate();
        this.repaint();
    }

    public void showPostalCodeFrame(CaissePanel caissePanel) {
        System.out.println("CaisseFrame.showPostalCodeFrame()");
        this.invalidate();
        final PostalCodeEditorPanel panel = new PostalCodeEditorPanel(this, caissePanel);
        final POSGlassPane glassPane2 = new POSGlassPane(panel, (getWidth() - panel.getPreferredSize().width) / 2, 100);
        this.setGlassPane(glassPane2);
        this.getGlassPane().setVisible(true);
        this.validate();
        this.repaint();

    }
}