OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 80 | Rev 93 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.action;
15
 
16
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic;
17
import org.openconcerto.erp.config.ComptaPropsConfiguration;
67 ilm 18
import org.openconcerto.erp.config.DefaultMenuConfiguration;
20 ilm 19
import org.openconcerto.erp.config.Gestion;
73 ilm 20
import org.openconcerto.erp.config.Log;
18 ilm 21
import org.openconcerto.erp.config.MainFrame;
80 ilm 22
import org.openconcerto.erp.config.MenuManager;
23
import org.openconcerto.erp.config.MinimalMenuConfiguration;
18 ilm 24
import org.openconcerto.erp.core.common.ui.PanelFrame;
25
import org.openconcerto.erp.core.common.ui.StatusPanel;
26
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
27
import org.openconcerto.erp.core.humanresources.payroll.element.CaisseCotisationSQLElement;
28
import org.openconcerto.erp.element.objet.ClasseCompte;
67 ilm 29
import org.openconcerto.erp.modules.ModuleFrame;
25 ilm 30
import org.openconcerto.erp.modules.ModuleManager;
18 ilm 31
import org.openconcerto.erp.panel.ComptaTipsFrame;
32
import org.openconcerto.erp.utils.NXDatabaseAccessor;
33
import org.openconcerto.map.model.Ville;
34
import org.openconcerto.sql.Configuration;
35
import org.openconcerto.sql.element.SQLElement;
36
import org.openconcerto.sql.model.SQLBackgroundTableCache;
37
import org.openconcerto.sql.model.SQLBase;
38
import org.openconcerto.sql.model.SQLRow;
39
import org.openconcerto.sql.model.SQLRowListRSH;
40
import org.openconcerto.sql.model.SQLSelect;
41
import org.openconcerto.sql.model.SQLTable;
42
import org.openconcerto.sql.model.UndefinedRowValuesCache;
43
import org.openconcerto.sql.model.Where;
26 ilm 44
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 45
import org.openconcerto.sql.preferences.UserProps;
20 ilm 46
import org.openconcerto.sql.sqlobject.IComboSelectionItem;
18 ilm 47
import org.openconcerto.sql.ui.ConnexionPanel;
48
import org.openconcerto.sql.users.User;
49
import org.openconcerto.sql.users.UserManager;
50
import org.openconcerto.sql.users.rights.TableAllRights;
51
import org.openconcerto.sql.users.rights.UserRightsManager;
52
import org.openconcerto.sql.users.rights.UserRightsManager.RightTuple;
83 ilm 53
import org.openconcerto.sql.utils.BackupPanel;
18 ilm 54
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
55
import org.openconcerto.ui.DefaultGridBagConstraints;
56
import org.openconcerto.ui.FrameUtil;
83 ilm 57
import org.openconcerto.ui.component.MutableListComboPopupListener;
18 ilm 58
import org.openconcerto.utils.ExceptionHandler;
59
import org.openconcerto.utils.JImage;
65 ilm 60
import org.openconcerto.utils.cc.IClosure;
67 ilm 61
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 62
 
63
import java.awt.Color;
64
import java.awt.GridBagConstraints;
65
import java.awt.GridBagLayout;
61 ilm 66
import java.awt.Image;
18 ilm 67
import java.awt.Insets;
68
import java.io.InputStream;
69
import java.util.ArrayList;
67 ilm 70
import java.util.Arrays;
18 ilm 71
import java.util.List;
67 ilm 72
import java.util.Locale;
18 ilm 73
import java.util.concurrent.CountDownLatch;
65 ilm 74
import java.util.concurrent.FutureTask;
73 ilm 75
import java.util.logging.Level;
18 ilm 76
 
77
import javax.swing.Action;
78
import javax.swing.JFrame;
79
import javax.swing.JOptionPane;
80
import javax.swing.JPanel;
81
import javax.swing.JTextArea;
82
import javax.swing.SwingUtilities;
83
import javax.swing.SwingWorker;
84
import javax.swing.UIManager;
85
 
86
public class NouvelleConnexionAction extends CreateFrameAbstractAction {
67 ilm 87
    private ConnexionPanel connexionPanel;
88
 
18 ilm 89
    public NouvelleConnexionAction() {
90
        super();
91
        this.putValue(Action.NAME, "Changer d'utilisateur");
92
    }
93
 
94
    public JFrame createFrame() {
95
        // needed as done() must come after us
96
        assert SwingUtilities.isEventDispatchThread();
97
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
98
 
99
        Runnable r = new Runnable() {
100
 
101
            public void run() {
102
                try {
67 ilm 103
                    TranslationManager.getInstance().addTranslationStreamFromClass(MainFrame.class);
104
                    TranslationManager.getInstance().setLocale(UserProps.getInstance().getLocale());
105
 
19 ilm 106
                    final Boolean booleanValue = UserProps.getInstance().getBooleanValue("HideTips");
107
                    if (!booleanValue) {
108
                        SwingUtilities.invokeLater(new Runnable() {
109
                            @Override
110
                            public void run() {
111
                                ComptaTipsFrame.getFrame(true).setVisible(true);
112
                            }
113
                        });
18 ilm 114
                    }
20 ilm 115
                    int selectedSociete;
116
                    if (NouvelleConnexionAction.this.connexionPanel != null && !Gestion.isMinimalMode()) {
117
                        selectedSociete = NouvelleConnexionAction.this.connexionPanel.getSelectedSociete();
118
                    } else {
119
                        selectedSociete = UserProps.getInstance().getLastSocieteID();
120
                        if (selectedSociete < SQLRow.MIN_VALID_ID) {
121
                            final SQLElement elem = comptaPropsConfiguration.getDirectory().getElement(comptaPropsConfiguration.getRoot().getTable("SOCIETE_COMMON"));
122
                            final List<IComboSelectionItem> comboItems = elem.getComboRequest().getComboItems();
123
                            if (comboItems.size() > 0)
124
                                selectedSociete = comboItems.get(0).getId();
125
                            else
126
                                throw new IllegalStateException("No " + elem + " found");
127
                        }
128
                    }
19 ilm 129
                    comptaPropsConfiguration.setUpSocieteDataBaseConnexion(selectedSociete);
25 ilm 130
                    try {
26 ilm 131
                        // create table if necessary
132
                        SQLPreferences.getPrefTable(comptaPropsConfiguration.getRootSociete());
67 ilm 133
                        SQLPreferences.startMemCached(comptaPropsConfiguration.getRootSociete());
26 ilm 134
                    } catch (Exception e) {
135
                        // don't die now, we might not need them
136
                        ExceptionHandler.handle("Impossible d'accéder aux préférences", e);
137
                    }
80 ilm 138
                    // needed by openEmergencyModuleManager()
139
                    UserRightsManager.getInstance().addRightForAdmins(new RightTuple(ModuleManager.MODULE_DB_RIGHT, true));
83 ilm 140
                    UserRightsManager.getInstance().addRightForAdmins(new RightTuple(BackupPanel.RIGHT_CODE, true));
67 ilm 141
                    // finish filling the configuration before going any further, otherwise the
142
                    // SQLElementDirectory is not coherent
80 ilm 143
                    ModuleManager.getInstance().setup(comptaPropsConfiguration.getRootSociete(), comptaPropsConfiguration);
67 ilm 144
                    try {
80 ilm 145
                        ModuleManager.getInstance().init();
67 ilm 146
                    } catch (Throwable e) {
147
                        // not OK to continue without required elements
148
                        openEmergencyModuleManager("Impossible de configurer les modules requis", e);
73 ilm 149
                        return;
67 ilm 150
                    }
80 ilm 151
                    MenuManager.setInstance((Gestion.isMinimalMode() ? new MinimalMenuConfiguration() : new DefaultMenuConfiguration()).createMenuAndActions());
25 ilm 152
 
83 ilm 153
                    final User user = UserManager.getInstance().getCurrentUser();
80 ilm 154
                    // Si l'utilisateur n'est pas superUser ou si il n'a pas de droit d'accéder
155
                    // à toutes les société
156
                    final int userId = user.getId();
157
                    if (!user.getRights().isSuperUser() && !user.getRights().haveRight("ACCES_ALL_SOCIETE")) {
158
                        final boolean emptyMeansAllow;
159
                        {
160
                            emptyMeansAllow = true;
161
                        }
26 ilm 162
 
80 ilm 163
                        final SQLTable tableAcces = comptaPropsConfiguration.getRoot().findTable("ACCES_SOCIETE");
164
                        SQLSelect sel = new SQLSelect();
165
                        sel.addSelectStar(tableAcces);
166
                        sel.setWhere(new Where(tableAcces.getField("ID_USER_COMMON"), "=", userId));
167
                        if (!emptyMeansAllow) {
168
                            sel.andWhere(new Where(tableAcces.getField("ID_SOCIETE_COMMON"), "=", selectedSociete));
169
                        }
170
 
171
                        final List<SQLRow> accessRows = SQLRowListRSH.execute(sel);
172
                        final boolean accessGranted;
173
                        if (!emptyMeansAllow) {
174
                            accessGranted = accessRows.size() > 0;
175
                        } else {
176
                            if (accessRows.size() == 0) {
177
                                accessGranted = true;
178
                            } else {
179
                                boolean tmp = false;
180
                                for (final SQLRow r : accessRows) {
181
                                    if (r.getInt("ID_SOCIETE_COMMON") == selectedSociete) {
182
                                        tmp = true;
183
                                        break;
184
                                    }
185
                                }
186
                                accessGranted = tmp;
187
                            }
188
                        }
189
 
190
                        if (!accessGranted) {
191
                            JOptionPane.showMessageDialog(null, "Vous n'avez pas les droits suffisants, pour accéder à cette société!");
192
                            return;
193
                        }
194
                    }
195
 
19 ilm 196
                    SwingUtilities.invokeLater(new Runnable() {
197
                        @Override
198
                        public void run() {
199
                            // even for quick login, check the license before displaying the main
200
                            // frame
18 ilm 201
 
83 ilm 202
                            MutableListComboPopupListener.setLockOverridable(user.getRights().isSuperUser());
203
 
19 ilm 204
                            StatusPanel.getInstance().fireStatusChanged();
67 ilm 205
                            final MainFrame f = new MainFrame();
19 ilm 206
                            String version = comptaPropsConfiguration.getVersion();
20 ilm 207
                            final String socTitle = comptaPropsConfiguration.getRowSociete() == null ? "" : ", [Société " + comptaPropsConfiguration.getRowSociete().getString("NOM") + "]";
208
                            f.setTitle(comptaPropsConfiguration.getAppName() + " " + version + socTitle);
19 ilm 209
                            f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
65 ilm 210
                        }
211
                    });
212
                    final FutureTask<?> showMainFrame = new FutureTask<Object>(new Runnable() {
213
                        @Override
214
                        public void run() {
80 ilm 215
                            // make sure the application is started with all required and mandatory
216
                            // modules
217
                            if (ModuleManager.getInstance().isInited()) {
67 ilm 218
                                final MainFrame mainFrame = MainFrame.getInstance();
73 ilm 219
                                mainFrame.initMenuBar();
67 ilm 220
                                FrameUtil.show(mainFrame);
221
                            }
65 ilm 222
                        }
223
                    }, null);
224
                    ModuleManager.getInstance().invoke(new IClosure<ModuleManager>() {
225
                        @Override
226
                        public void executeChecked(ModuleManager input) {
25 ilm 227
                            // start modules before displaying the frame (e.g. avoid modifying a
228
                            // visible menu bar)
229
                            try {
65 ilm 230
                                input.startRequiredModules();
80 ilm 231
                                try {
232
                                    input.startPreviouslyRunningModules();
233
                                } catch (Exception exn) {
234
                                    // OK to start the application without all modules started
235
                                    // but don't continue right away otherwise connexion panel will
236
                                    // be closed and the popup with it
237
                                    try {
238
                                        ExceptionHandler.handle(NouvelleConnexionAction.this.connexionPanel, "Impossible de démarrer les modules", exn).getDialogFuture().get();
239
                                    } catch (Exception e) {
240
                                        e.printStackTrace();
241
                                    }
242
                                }
67 ilm 243
                                SwingUtilities.invokeLater(showMainFrame);
25 ilm 244
                            } catch (Exception exn) {
67 ilm 245
                                openEmergencyModuleManager("Impossible de démarrer les modules requis", exn);
25 ilm 246
                            }
18 ilm 247
                        }
19 ilm 248
                    });
80 ilm 249
                    initCache(comptaPropsConfiguration);
65 ilm 250
                    // don't close ConnexionPanel until the main frame is shown
251
                    showMainFrame.get();
19 ilm 252
                } catch (Throwable e) {
83 ilm 253
                    if (e.getMessage() != null && e.getMessage().contains("TR_BON_DE_LIVRAISON not found")) {
254
                        JOptionPane.showMessageDialog(new JFrame(), "Votre base de données n'est pas à jour.\nUtilisez l'outil de configuration et pensez à l'achat du manuel!!!");
255
                        return;
256
                    }
19 ilm 257
                    ExceptionHandler.handle("Erreur de connexion", e);
258
                }
18 ilm 259
            }
260
 
261
        };
262
 
263
        final JImage image = new JImage(ComptaBasePropsConfiguration.class.getResource("logo.png"));
61 ilm 264
        Image customImage = ComptaPropsConfiguration.getInstanceCompta().getCustomLogo();
265
        if (customImage != null) {
266
            image.setImage(customImage);
267
        }
18 ilm 268
        image.setBackground(Color.WHITE);
269
        JPanel p = new JPanel();
270
 
271
        p.setLayout(new GridBagLayout());
272
        GridBagConstraints c = new DefaultGridBagConstraints();
273
        c.weightx = 1;
274
        c.weighty = 1;
275
        c.insets = new Insets(0, 0, 0, 0);
276
        c.fill = GridBagConstraints.BOTH;
277
 
20 ilm 278
        this.connexionPanel = ConnexionPanel.create(r, image, !Gestion.isMinimalMode());
18 ilm 279
        if (this.connexionPanel == null)
280
            return null;
67 ilm 281
        this.connexionPanel.initLocalization(getClass().getName(),
282
                Arrays.asList(Locale.FRANCE, Locale.CANADA_FRENCH, new Locale("fr", "CH"), new Locale("fr", "BE"), Locale.UK, Locale.CANADA, Locale.US, Locale.GERMANY, new Locale("de", "CH")));
18 ilm 283
 
284
        p.add(this.connexionPanel, c);
285
        final PanelFrame panelFrame = new PanelFrame(p, "Connexion");
286
        panelFrame.setLocationRelativeTo(null);
287
        panelFrame.pack();
288
        panelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
289
        return panelFrame;
290
    }
291
 
80 ilm 292
    private void initCache(final ComptaPropsConfiguration comptaConf) {
293
        final SQLBase baseSociete = comptaConf.getSQLBaseSociete();
18 ilm 294
        Thread t = new Thread() {
295
            @Override
296
            public void run() {
297
                // laisse le temps au logiciel de demarrer
298
                try {
299
                    Thread.sleep(1000);
300
                } catch (InterruptedException e) {
301
                    e.printStackTrace();
302
                }
303
                ClasseCompte.loadClasseCompte();
304
                CaisseCotisationSQLElement.getCaisseCotisation();
305
 
306
                Ville.init(new NXDatabaseAccessor());
307
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TAXE"), 600);
308
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("PREFS_COMPTE"), 600);
73 ilm 309
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMPTE_PCE"), 600);
18 ilm 310
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("JOURNAL"), 600);
311
 
312
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMMERCIAL"), 600);
313
 
314
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TYPE_REGLEMENT"), 1000);
67 ilm 315
                SQLBackgroundTableCache.getInstance().startCacheWatcher();
316
 
18 ilm 317
                TaxeCache.getCache();
318
 
67 ilm 319
                final UndefinedRowValuesCache undefCache = UndefinedRowValuesCache.getInstance();
320
                final List<SQLTable> tablesToCache = new ArrayList<SQLTable>();
321
                tablesToCache.add(baseSociete.getTable("DEVIS"));
322
                tablesToCache.add(baseSociete.getTable("ETAT_DEVIS"));
323
                tablesToCache.add(baseSociete.getTable("FAMILLE_ARTICLE"));
324
                tablesToCache.add(baseSociete.getTable("ADRESSE"));
325
                tablesToCache.add(baseSociete.getTable("DEVIS_ELEMENT"));
326
                tablesToCache.add(baseSociete.getTable("CONTACT"));
327
                tablesToCache.add(baseSociete.getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
328
                tablesToCache.add(baseSociete.getTable("SAISIE_KM_ELEMENT"));
329
                tablesToCache.add(baseSociete.getTable("BON_DE_LIVRAISON_ELEMENT"));
330
                tablesToCache.add(baseSociete.getTable("COMMANDE_CLIENT_ELEMENT"));
331
                tablesToCache.add(baseSociete.getTable("AVOIR_CLIENT_ELEMENT"));
332
                tablesToCache.add(baseSociete.getTable("BON_RECEPTION_ELEMENT"));
333
                undefCache.preload(tablesToCache);
18 ilm 334
            }
335
 
336
        };
337
        t.setName("Cache preload");
338
        t.setDaemon(true);
339
        t.setPriority(Thread.MIN_PRIORITY);
340
        t.start();
341
    }
342
 
343
    private String checkLicense(final SwingWorker<String, Object> w) {
344
        try {
345
            return w.get();
346
        } catch (Exception e) {
347
            throw ExceptionHandler.die("Impossible de charger la licence.", e);
348
        }
349
    }
350
 
73 ilm 351
    private void openEmergencyModuleManager(final String str, final Throwable e) {
352
        Log.get().log(Level.SEVERE, "Normal startup impossible, opening the module manager in order to resolve the issue.", e);
67 ilm 353
        SwingUtilities.invokeLater(new Runnable() {
354
            @Override
355
            public void run() {
73 ilm 356
                ExceptionHandler.handle(str, e);
80 ilm 357
                // can't start since there's no main frame (and obviously no modules can be stopped
358
                // since none are running)
359
                final ModuleFrame fMod = ModuleFrame.createInstallOnlyInstance();
73 ilm 360
                fMod.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
361
                fMod.setTitle(str);
80 ilm 362
                FrameUtil.show(fMod);
67 ilm 363
            }
364
        });
365
    }
18 ilm 366
}